简体   繁体   中英

Python - how to get JSON from a GraphQL api?

I'm trying to create a simple Python script that should just query a GraphQL api and retrieve JSON data from it. The problem with my code is that i keep getting an HTML response whereas i need to get JSON data.

If i execute the GraphQL api from here , the page will receive a JSON response (i can see it from Chrome devtools as well), but if i do the same from my Python code, i will get an html response:

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'])

Response: text/html

I tried to send the query as a POST request payload, but the output is the same. How can i retrieve the JSON data from my Python script too? Thanks in advance!

You have to send a POST request with a json body.

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM