rhttrjsonlite

Body of a POST request


i'm trying to make a request to get the Acess Token, as described in the second step at https://developers.anbima.com.br/en/visao-geral/autenticacao/

The problem is with the variable body_anbima, the value expected at the server is like

REQUEST BODY
{
"grant_type": "client_credentials"
}

I tried many differents ways to write, but the better i could get was

"grant_type:client_credentials"
"{\"grant_type\":\"client_credentials\"}"

This is the code i'm using

library(httr)
library(jsonlite)

token_anbima <- base64_enc("aC2yaac23:1bhS45TT")
body_anbima <- {"grant_type:client_credentials"}

res <- POST('https://api.anbima.com.br/oauth/access-token',
            add_headers("Content-Type"="application/json",
                        "Authorization"= paste("Basic", token_anbima)), 
            body = toJSON(body_anbima, auto_unbox=TRUE),
            encode = 'json',
            verbose()
            )

res

rawToChar(res$content)

Solution

  • Using this code

    library(httr)
    
    base64_value <- openssl::base64_encode("your_client_id:your_client_secret")
    
    response <- 
      POST(url = "https://api.anbima.com.br/oauth/access-token",
           add_headers(Authorization = paste("Basic", base64_value)),
           body = list(grant_type = "client_credentials"),
           encode = "form")
    
    response$status
    content(response, "text")
    

    Result

    $ rscript token.R
    [1] 201
    [1] "{\"access_token\":\"**real_token**\",\"token_type\":\"access_token\",\"expire
    s_in\":3600}"
    
    

    You can test by Postman enter image description here

    enter image description here