Python - 如何从 GraphQL api 中获取 JSON?

Python - how to get JSON from a GraphQL api?

我正在尝试创建一个简单的 Python 脚本,它应该只查询 GraphQL api 并从中检索 JSON 数据。我的代码的问题是我不断收到 HTML 响应,而我需要获取 JSON 数据。

如果我从 here 执行 GraphQL api,该页面将收到 JSON 响应(我也可以从 Chrome devtools 看到它),但是如果我从我的 Python 代码中做同样的事情,我将得到一个 html 响应:

import requests
import json
import time

query = {'query': '{saleAuctions(allowedAddresses: ["0xdc65d63cdf7b03b95762706bac1b8ee0af130e8b", "0x0000000000000000000000000000000000000000"]) {id}}'}
r = requests.get('https://graph.defikingdoms.com/subgraphs/name/defikingdoms/apiv5', params=query)

print(r.headers['content-type'])

响应:text/html

我尝试将查询作为 POST 请求负载发送,但输出是相同的。我怎样才能从我的 Python 脚本中检索 JSON 数据?提前致谢!

您必须发送带有 json 正文的 POST 请求。

import requests
import json
import time

query = json.dumps({'query': '{saleAuctions(allowedAddresses: ["0xdc65d63cdf7b03b95762706bac1b8ee0af130e8b", "0x0000000000000000000000000000000000000000"]) {id}}'})
r = requests.post('https://graph.defikingdoms.com/subgraphs/name/defikingdoms/apiv5', data=query)

print(r.headers['content-type'])