'how to attach the token to a graphql mutation request?
I create this function to update details of user, before this function I have to login and get the token that I have to use in the next call.
I use this for init:
# Select your transport with a defined url endpoint
transport = AIOHTTPTransport(url=HOSTNAME_GRAPHQL, headers={'Authorization': 'token'})
# Create a GraphQL client using the defined transport
client = Client(transport=transport, fetch_schema_from_transport=True)
and this funcion for call the mutation
def mutation_updateUser(client, id, username, firstName, lastName, access_token):
# headers = {
# #"X-Shopify-Storefront-Access-Token": access_token
# "Authorization": "Bearer " + access_token
# }
headers={'Authorization': f'Bearer ' + access_token}
query = gql(
"""
mutation updateUser($input: UpdateUserInput!) {
updateUser(input: $input) {
id
email
username
lastName
firstName
role
avatar
}
}
"""
)
params = {
"input": {
"id": id,
"username": username,
"firstName": firstName,
"lastName": lastName
}
}
request = client.execute(query, variable_values=params, headers=headers)
if request.status_code == 200:
return request.json()
else:
raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))
#return result
when I run the program I got this error: **
Si è verificata un'eccezione: TypeError
execute() got an unexpected keyword argument 'headers'
File "D:\Python project\API ReadyTGo\mutation_updateUser.py", line 36, in mutation_updateUser
request = client.execute(query, variable_values=params, headers=headers)
**
SOLVED THE PROBLEM!!
I modify the function like this:
from gql.transport.aiohttp import AIOHTTPTransport
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
from questions import HOSTNAME_GRAPHQL
def mutation_updateUser(id, username, firstName, lastName, access_token):
# headers = {
# #"X-Shopify-Storefront-Access-Token": access_token
# "Authorization": "Bearer " + access_token
# }
#headers={'Authorization': f'Bearer ' + access_token}
headers = {"Authorization": f"Bearer {access_token}"}
_transport = RequestsHTTPTransport(url=HOSTNAME_GRAPHQL, use_json=True, headers=headers)
client = Client(transport=_transport, fetch_schema_from_transport=True)
query = gql(
"""
mutation updateUser($input: UpdateUserInput!) {
updateUser(input: $input) {
id
email
username
lastName
firstName
role
avatar
}
}
"""
)
params = {
"input": {
"id": id,
"username": username,
"firstName": firstName,
"lastName": lastName
}
}
request = client.execute(query, variable_values=params)
return request.json()
I hope to help someone
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|