【问题标题】:Python - how to get JSON from a GraphQL api?Python - 如何从 GraphQL api 获取 JSON?
【发布时间】:2021-12-26 02:50:15
【问题描述】:

我正在尝试创建一个简单的 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 数据?提前致谢!

【问题讨论】:

    标签: python python-requests graphql


    【解决方案1】:

    您必须发送带有 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'])
    

    【讨论】:

    • 哇,这成功了!非常感谢穆萨!
    猜你喜欢
    • 2021-06-27
    • 2018-02-25
    • 1970-01-01
    • 2018-10-21
    • 2021-11-05
    • 2021-07-27
    • 2022-11-30
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多