How do you handle graphql query and fragment in python? - python

I am trying to query using the requests library but am having trouble. I suspect it's to do with the handling of the fragment but I'm not sure.
When I run the code I get Response 400. Here is my code:
import requests
import json
query = """query GetAxieTransferHistory($axieId: ID!, $from: Int!, $size: Int!) {
axie(axieId: $axieId) {
id
transferHistory(from: $from, size: $size) {
...TransferRecords
__typename
}
__typename
}
}
fragment TransferRecords on TransferRecords {
total
results {
from
to
timestamp
txHash
withPrice
__typename
}
__typename
}"""
params = {
"axieId": "9082310",
"from": 0,
"size": 1
}
url = 'https://axieinfinity.com/graphql-server-v2/graphql'
r = requests.post(url, json={"query": query, "params": params})
print(r.status_code)
Thanks in advance!

Try changing your params key to variables
r = requests.post(url, json={"query": query, "variables": params})

Related

How to get the value of "authorization" from Json using python?

I have a Json data, where I want to get the value of "authorization" i.e "OToken
DEDC1071B77800A146B6E8D2530E0429E76520C151B40CC3325D8B
6D9242CBA3A6BFA643E7E5596FBEBAE0F46A1FB1BCD099EBC1F59D
CD82F390B6BC45FCE036F37F7F589BD687A691E1378F1FF432331C
62E7E641E857C8F8A405A4BFE2F01B1EB8F3C69817D45F5DDE9DEE
346ACABA1B7208DECA9E43CCE7AB3761553E23D9CB36A870C1819C
15C7C4B1CFE2802DFD05F651AA537AB81787.4145535F55415431" using python
{
"links":[
{
"method":"GET",
"rel":"self",
"href":"https://www.sampleurl.com/request"
},
{
"headers":{
"authorization":"OToken
DEDC1071B77800A146B6E8D2530E0429E76520C151B40CC3325D8B
6D9242CBA3A6BFA643E7E5596FBEBAE0F46A1FB1BCD099EBC1F59D
CD82F390B6BC45FCE036F37F7F589BD687A691E1378F1FF432331C
62E7E641E857C8F8A405A4BFE2F01B1EB8F3C69817D45F5DDE9DEE
346ACABA1B7208DECA9E43CCE7AB3761553E23D9CB36A870C1819C
15C7C4B1CFE2802DFD05F651AA537AB81787.4145535F55415431"
},
"valid_date":"2020-08-17T15:49:00+0530",
"method":"POST",
"rel":"redirect",
"href":"https://www.billdesk.com/pgi/MerchantPayment/",
"parameters":{
"mercid":"BDMERCID",
"bdorderid":"OAFC19XTFD8TSP"
}
}
]
}
import json
response = YOUR_JSON_STRING
data = json.loads(response)
authorization = data['headers']['authorization']

response 422 after trying to send post request with json file

I have been trying to find an answer that work on my case but had no success.
I am getting a response 422 when running the code below. I have replaced the json in the response variable and also used json.dumps around the data variable but I am still getting this response. Would you be able to find the issue within my json file? Thanks a lot
todaystr = datetime.today().strftime('%Y-%m-%d')
today = datetime.strptime(todaystr, '%Y-%m-%d')
first_day_of_month = today.replace(day=1)
day_count_str = today - first_day_of_month
day_count_int = day_count_str / timedelta(days=1)
day_count_split = str(day_count_int)
sep = '.'
day_count = day_count_split.split(sep, 1)[0]
dt = str(first_day_of_month.timestamp())
data = {"requestId": "numberOfUniqueAccountsAndVisitors", "timeSeries": {"period": "dayRange", "count": day_count, "first": dt}, "source": {"events": None}, "pipeline": [{"reduce": [{"reduce": {"visitors": {"count": "visitorId"}, "accounts": {"count": "accountId"}}}]}]}
headers = {
'x-pendo-integration-key': API_Key,
'content-type': "application/json"
}
response = requests.post(url, json=data, headers=headers)
print(response)
response_dictionary = json.loads(response.content)
print(response_dictionary)
In the payload to the Pendo Aggregation API, the request object should not be an array. And make sure the "key" should be named as "request"(singular), not as "requests"(plural).
Try something like this
{
"response": {
"mimeType": "application/json"
},
"request": {
"name": "accounts-last7days",
"requestId": "accounts-last7days"
}
}

Is there a requests function that allows to extract only a portion of a JSON response from an api?

I have this giant response and I just need the IDs in "SingleItemOffers" at the end of the response (I had to cut down a lot of the json reponse due to stack overflow):
{
"FeaturedBundle": {
"Bundle": {
"ID": "2b18d53c-6173-460e-bb72-63bbb114b182",
"DataAssetID": "441117e1-40be-42e2-3aeb-49957e5c03fd",
"CurrencyID": "85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741",
"Items": [
{
"Item": {
"ItemTypeID": "e7c63390-eda7-46e0-bb7a-a6abdacd2433",
"ItemID": "291cb44a-410d-b035-4d0b-608a92c2cd91",
"Amount": 1
},
"BasePrice": 1775,
"CurrencyID": "85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741",
"DiscountPercent": 0.33,
"DiscountedPrice": 1189,
"IsPromoItem": false
}
]
},
"BundleRemainingDurationInSeconds": 804392
},
"SkinsPanelLayout": {
"SingleItemOffers": [
"5a0cd3b5-4249-bf6f-d009-17a81532660e",
"7e44fc1b-44fa-cdda-8491-f8a5bca1cfa3",
"daa73753-4b56-9d21-d73e-f3b3f4c9b1a6",
"f7425a39-43ca-e1fe-5b2b-56a51ed479c5"
],
"SingleItemOffersRemainingDurationInSeconds": 37592
}
}
This is my code at the moment and when I print the reponse it prints the entire thing:
import requests
import json
url = "https://pd.na.a.pvp.net/store/v2/storefront/XXX"
payload={}
headers = {
'X-Riot-Entitlements-JWT': 'XXX',
'Authorization': 'XXX'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
Maybe you can try this:
response[0]["FeaturedBundle"]["Bundle"]["ID"]
you can use it specifically with a FOR loop to change the sub index and get a longer response, I hope it helps you, greetings.

Graphql query in Python

Here is a graphql query with its result : OK.
I try to get the same result with Python, but I get nothing : response.text is empty. (API key is not needed).
q = """
{
node(id: "UXVlc3Rpb25uYWlyZTo5NTNjYjdjYS0xY2E0LTExZTktOTRkMi1mYTE2M2VlYjExZTE=") {
... on Questionnaire {
replies(first: 10, after: null) {
totalCount
pageInfo {
hasNextPage
endCursor
}
edges {
node {
id
createdAt
publishedAt
updatedAt
author {
id
}
responses {
question {
title
}
... on ValueResponse {
value
}
}
}
}
}
}
}
}
"""
response = requests.post(url = "https://granddebat.fr/graphql" , json = {'query': q})
print(response.text)
Please, any idea ?
It's all good with the query itself. In request you need to pass headers with {'Accept':
'application/vnd.cap-collectif.preview+json'}
response = requests.post(
url = "https://granddebat.fr/graphql",
json = {'query': q,},
headers= {'Accept': 'application/vnd.cap-collectif.preview+json'}
)

JSONDecodeError: Expecting value: line 1 column 1 (char 0) error

I am facing this error while making request to fetch json from api.
I can get json data using the "/v1/articles' path.
conn = http.client.HTTPSConnection("api.xxxx.com.tr")
headers = {
'accept': "application/json",
'apikey': "cd6b6c96799847698d87dec9f9a731d6"
}
filter = "daily"
conn.request("GET", "/v1/articles", headers=headers)
reader = codecs.getreader("utf-8")
res = conn.getresponse()
data = json.load(reader(res))
json.dumps(data)
return data
But i am having JSONDecodeError if i set filter. Code:
conn = http.client.HTTPSConnection("api.xxxx.com.tr")
headers = {
'accept': "application/json",
'apikey': "cd6b6c96799847698d87dec9f9a731d6"
}
conn.request("GET", "/v1/articles?$filter=Path eq '/daily/'", headers=headers)
reader = codecs.getreader("utf-8")
res = conn.getresponse()
data = json.load(reader(res))
json.dumps(data)
return data
I tried same filter using Postman with no error and i can get Json data.
Returned Json data from Postman:
[
{
"Id": "40778196",
"ContentType": "Article",
"CreatedDate": "2018-03-20T08:28:05.385Z",
"Description": "İspanya'da 2016 yılında çalınan lüks otomobil, şasi numarası değiştirilerek Bulgaristan üzerinden getirildiği Türkiye'de bulundu.",
"Files": [
{
"FileUrl": "http://i.xxxx.com/i/xxxx/98/620x0/5ab0c6a9c9de3d18a866eb54.jpg",
"Metadata": {
"Title": "",
"Description": ""
}
}
],
"ModifiedDate": "2018-03-20T08:32:12.001Z",
"Path": "/gundem/",
"StartDate": "2018-03-20T08:32:12.001Z",
"Tags": [
"ispanya",
"Araç",
"Hırsız",
"Dolandırıcı"
],
"Title": "İspanya'da çalınan lüks araç Türkiye'de bulundu!",
"Url": "http://www.xxxx.com.tr/gundem/ispanyada-calinan-luks-arac-turkiyede-bulundu-40778196"
}
]
I can not figure out the problem. It would be great if anyone help me about this issue. Thank you.
I finally figured out the problem! Using the requests library have solved my problem now I can filter the api request.
data = requests.get('https://api.xxxxx.com.tr/v1/articles', headers =
headers, params={"$filter":"Path eq '/xxxxxx/'"}).json()
I am leaving this answer here for anyone else who can need this solution in the future.
Thanks for all your suggestions.
The problem is in the following line
data = json.load(reader(res))
when your response is not a json string, JSONDecodeError occurs. so, add an additional logic to see if the response is None or a json string. First thing, print the reader(res) and see what the return is

Categories

Resources