Search code examples
rresthttr

Consume a REST API with R using a Token


I want to consume a REST API and have to perform the following steps for it.

  1. I have to get a Token using my UserName and Password (What I have accomplished successfully and the token is stored in a variable)
  2. I have to use this Token to get data from the API and here I stuck.

I have tried

req_token <- THE TOKEN I HAVE RECIEVED ALREADY
url <- 'https://myService.com/web/api/datasources/{identifier}/data'
mydata <- GET(url, config = add_headers(paste0("Basic ", req_token)))

The identifier is there to specify a datasource within many, so in my case I had to replace it with EdQVFcgRGF0 (sort like). So I end up with the url

https://myService.com/web/api/datasources/{EdQVFcgRGF0}/data

All specification I got from the provider was

/datasources/{identifier]/data (GET)
● get data for one datasource (full data)

I tried consume the api with vb.net first and sending the token in the header works

request.AddHeader("Authorization", "Basic " + _token)

Now I get an 401 Unauthorized using R and do not know, what is wrong, anyone who can help me out?


Solution

  • Depending on the API configuration, I think you'll add it in where there's the curly brackets for {identifier} in the URL.

        req_token <- THE TOKEN I HAVE RECIEVED ALREADY
        url <- paste('https://myService.com/web/api/datasources/', req_token, '/data', sep='')
    

    That's how some API's do it. Which means your headers might not look like this any more.

    mydata <- GET(url, config = add_headers(paste0("Basic ", req_token)))
    

    They probably just won't be there any more. So like :

    mydata <- GET(url)
    

    If the token is required in the headers it might look more like this:

    mydata <- GET(url, config = add_headers("Basic " = req_token))
    

    But I doubt the token will be both in the URL and in the header. You'll have to find out which is required from the docs.

    Edit

    I believe your headers should look like this:

    mydata <- GET(url, config = add_headers("Authorization " = paste( "Basic", req_token, sep = ' ' ))