Python GraphQL gql client authentication

5.7k Views Asked by At

I´m having hard time to use GraphQL with Python since the suggested library: gql is completely undocumented.

How ever I found out that to provide the api url I need to pass a RequestsHTTPTransport object to Client like this:

client = Client(transport=RequestsHTTPTransport(url='https://some.api.com/v3/graphql'))

but how to provide credentials like the Bearer Key?

PS I noticed that it RequestsHTTPTransport accepts also a auth param which is described as:

:param auth: Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth

how ever I still can not find out how to create this tuple or callable to work with a Bearer Key :(

Thanks in advise

2

There are 2 best solutions below

1
On BEST ANSWER

You can add it in the headers.

reqHeaders = {
    'x-api-key' : API_KEY,
    'Authorization': 'Bearer ' + TOKEN_KEY // This is the key
}

_transport = RequestsHTTPTransport(
    url=API_ENDPOINT,
    headers = reqHeaders,
    use_json=True,
)

client = Client(
    transport = _transport,
    fetch_schema_from_transport=True,
)
0
On

I am able to authenticate using the Bearer Access Token and retrieve the data of a Graphql query successfully using the below Python script.

import requests
import json
import urllib3
from urllib3.util.ssl_ import create_urllib3_context

ctx = create_urllib3_context()
ctx.load_default_certs()
ctx.options |= 0x4 

BASE_URL = 'url_here'

 
def authenticate():
    query = """
            query here
            """
    access_token = "access token here"

    # print(f'Access token: {access_token}')
    headers = {'Authorization': f'Bearer {access_token}'}

 
    with urllib3.PoolManager(ssl_context=ctx) as http:
        req = http.request("POST", BASE_URL, json = {'query': query}, headers = headers)
        print(req.data)      
 


if __name__=="__main__":
    authenticate()