Python请求在处理带有变量的Graphql查询时抛出400



我正在尝试使用Python中的内置请求模块来运行graphql查询。

# prepare the query with parameters
def get_user(by):
try:
variables = {
"email": "test@test.com"
}
user_query = """
{
getUser($email:String) {
userId
email
firstName
lastName
phoneNumber
department
officeLocation
isAvailable
updatedAt
}
}
"""
path = resolve_url('users', site_id='hub')
# Run gql query
user_data = run_query(user_query, variables=variables, path=path, by=by)
return user_data
except Exception as ex:
raise exc.BadRequest(
'Could not parse the response. Following exception occurred :: {}'.format(ex)
)

客户端运行gql查询

def run_query(query: str, variables: dict, path: str, by=None):
token = 'some-token'
headers = {'x-internal-api-key': 'Bearer {}'.format(token)}
json = dict({'query': query})
if variables:
json['variables'] = variables
response = requests.post(path, json=json, headers=headers) # Throws 400
if response.status_code == 200:
return response.json()
else:
raise Exception("Query failed to run: {} - {}".format(response.status_code, response.json()))

这将抛出400 - {'message': 'Syntax Error: Expected Name, found $'...}。当传递硬编码值时,查询工作得非常好,因此查询本身没有问题。

请帮助我了解问题所在或提出替代方案。我已经浏览了多个链接来了解如何在查询中传递变量,但似乎都不起作用。

好了,终于解决了问题。似乎必须首先向查询声明变量,然后在graphql查询中的任何位置使用这些变量。这是修复:

user_query = """
>>>query($email: String!){<<<
getUser(email: $email) {
userId
email
firstName
lastName
phoneNumber
department
officeLocation
isAvailable
updatedAt
}
}
"""

希望有更好的记录。

好吧,如果你真的认为你的参数是正确的。

有两种方法你可以尝试(我不确定它会解决你的问题,但你可以尝试(:

(尽量不要使用json作为变量,因为它与json模块同名(更改发布代码:

json = dict({'query': query})
response = requests.post(path, json=json, headers=headers)

至:

params = {'query':'''
viewer {
name
}
}'''}
response = requests.get(path,params=params)

也许是因为query是一个get方法而不是post方法。(如果没有,您可以尝试post(

最新更新