使用Python Requests调用Wiki.js GraphQL API时如何使用变量?
问题描述
使用Python的requests包调用Wiki.js的GraphQL API创建用户时,硬编码参数可以正常创建,但尝试用字符串插值方式传入变量时失败。以下是尝试的代码:
# we have imported the requests module import requests # defined a URL variable that we will be # using to send GET or POST requests to the API url = "https://wiki.something.com/graphql/" email = "uchiha.sasuke@example.com" name = "Uchiha Sasuke" body = """ mutation { users { create ( email: "{email}" name: "{name}" passwordRaw: "pass123$" providerKey: "local" groups: [1] mustChangePassword: true sendWelcomeEmail: false ) { responseResult { succeeded slug message } user { id } } } } """ response = requests.post(url=url, json={"query": body}, headers={"Authorization": "Bearer ..."}) print("response status code: ", response.status_code) if response.status_code == 200: print("response : ", response.content)
解决方案
问题出在你用Python字符串插值的方式传递参数,这不符合GraphQL的变量规范,API无法正确解析这些参数。正确的做法是使用GraphQL的变量机制,具体步骤如下:
- 第一步:修改mutation定义,在开头声明变量(用
$前缀),并在对应的参数位置引用这些变量 - 第二步:在请求的JSON中单独添加
variables字段,传入变量的实际值
修正后的完整代码:
import requests url = "https://wiki.something.com/graphql/" email = "uchiha.sasuke@example.com" name = "Uchiha Sasuke" # 定义带变量的mutation body = """ mutation CreateUser($email: String!, $name: String!) { users { create ( email: $email name: $name passwordRaw: "pass123$" providerKey: "local" groups: [1] mustChangePassword: true sendWelcomeEmail: false ) { responseResult { succeeded slug message } user { id } } } } """ # 请求时同时传入query和variables response = requests.post( url=url, json={ "query": body, "variables": { "email": email, "name": name } }, headers={"Authorization": "Bearer ..."} ) print("response status code: ", response.status_code) if response.status_code == 200: print("response : ", response.content)
失败原因说明
- 字符串插值易引发格式错误:如果变量包含特殊字符(比如引号、换行),会直接破坏GraphQL查询的语法结构,导致API解析失败
- 不符合GraphQL变量规范:Wiki.js的GraphQL API要求变量通过
variables字段单独传递,而非直接嵌入到query字符串中
内容的提问来源于stack exchange,提问作者Karthik Bhandary
相关产品推荐
相关产品推荐

