Sudhakar Samak
Sudhakar Samak

Reputation: 399

Consuming API with graphql queries throwing 401 error on R but working fine on Python

I have a requirement to access some information through an API. I need to do this on R. I tried doing on Python and it worked just fine but facing 401 error while doing the same operation on R.

I have the API key and also know the query to be performed. I have attached both Python and R code below.

Python:

import requests

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
}

query = """
{
    boards (ids: 157244624) {
        permissions
    }
}
"""

response = requests.get('https://XYZwebsite.com/', headers=headers, json={'query': query})

R:

require(httr)

headers = c(
  `Content-Type` = 'application/json',
  `Authorization` = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
)

data = '{
    boards (ids: 157244624) {
        permissions
    }
}'

res <- GET(url = 'https://XYZwebsite.com/', add_headers(.headers=headers), body = data)

Am i missing out something in the R code? It looks pretty much the same but i am getting a 401 error on R for some weird reason.

Upvotes: 1

Views: 8327

Answers (2)

Coni
Coni

Reputation: 1

In my case api key was expired... really long journey let me to:

  1. amplify update api
  2. walk through all
  3. choose api key
  4. enter new api key name
  5. enter 365 days no further changes
  6. amplify push will not detect changes, so use amplify push --force maybe it helps

Upvotes: 1

AidanGawronski
AidanGawronski

Reputation: 2085

Perhaps try:

r <- GET("https://XYZwebsite.com/", 
         add_headers(`Content-Type` = "application/json",
                     `Authorization` = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"),
         body = data)

Edit: With the gist you are working off of:

Authenticate first:

token <- GQL(auth_query)$authenticate$jwtToken

Then you can run your queries by passing the token you get in the response:

GQL(current_person_query, .token = token)

Seems like you are trying to do two things at once.

If you already have the token then it looks like you are passing it incorrectly:

auth_header <- paste("bearer", .token)
res <- POST(.url, body = pbody, encode="json", add_headers(Authorization=auth_header), ...)

As it should be passed as "bearer XXXXXXXXXXXXXXXXX".

Upvotes: 0

Related Questions