Home > Blockchain >  Python - how to get JSON from a GraphQL api?
Python - how to get JSON from a GraphQL api?

Time:11-15

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!

CodePudding user response:

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