Graphql query in Python - 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'}
)

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

How do you handle graphql query and fragment in 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})

Python to GAS translation not working: get bad request error

I want the following code to be translated into GAS from python. I wrote the GAS version pasted below but it is not working. It must be something simple but I don't know the reason why I get this error. Any advice will be appreciated. Thanks.
import requests
requestId = "*******************"
url = "http://myapi/internal/ocr/"+requestid+"/ng"
payload={}
headers = {
'X-Authorization': 'abcdefghijklmn'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I wrote this at the moment but I get bad request error.
function sending(yesorno, requestId) {
var requestId = "*******************"
 var STAGING_KEY = "abcdefghijklmn"
var url = url = "http://myapi/internal/ocr/"+requestId+"/ng"
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': JSON.stringify(data),
'headers': {
'X-Authorization': STAGING_KEY
}
};
//Error processing
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options));
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error')
}
}
Modified Code
function sending() {
var requestId = "*************************"
var STAGING_KEY = "abcdefghijklmn"
var url = "http://myapi/internal/ocr/"+requestId+"/ng";
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': data,
'headers': {
'X-Authorization': STAGING_KEY
}
};
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
Logger.log(response)
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error1')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error2: '+ e.toString())
}
}
Error
error2: Exception: Bad request:
I understood your situation as follows.
Your python script works fine.
You want to convert the python script to Google Apps Script.
When your Google Apps Script is run, an error Exception: Bad request: occurs.
In this case, how about the following modification? When response = requests.request("POST", url, headers=headers, data=payload) is used with payload={}, I think that at Google Apps Script, it's 'payload': {}.
Modified script:
function sending() {
var requestId = "*******************"
var STAGING_KEY = "abcdefghijklmn"
var url = "http://myapi/internal/ocr/" + requestId + "/ng"
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': data,
'headers': {
'X-Authorization': STAGING_KEY
}
};
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
console.log(response)
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error')
}
}
Note:
By the above modification, the request of Google Apps Script is the same as that of the python script. But if an error occurs, please check the URL and your STAGING_KEY, again. And, please check whether the API you want to use can access from the Google side.
Reference:
fetch(url, params)

Getting error while Formatting request query in Python

I am trying to request a Graphql API through python. I have written the script which is trying to pull audit log from Github for each organisation.
This is the Python script I have written.
Query = """
query {
organization(login: '{}') {
auditLog(first: 100, '{}') {
edges {
node {
... on RepositoryAuditEntryData {
repository {
name
}
}
... on OrganizationAuditEntryData {
organizationResourcePath
organizationName
organizationUrl
}
... on TeamAuditEntryData {
teamName
}
... on TopicAuditEntryData {
topicName
}
... on OauthApplicationAuditEntryData {
oauthApplicationName
}
... on EnterpriseAuditEntryData {
enterpriseResourcePath
enterpriseUrl
enterpriseSlug
}
... on AuditEntry {
actorResourcePath
action
actorIp
actorLogin
operationType
createdAt
actorLocation {
countryCode
country
regionCode
region
city
}
#User 'Action' was performed on
userLogin
userResourcePath
userUrl
}
}
cursor
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
}
}
}
}
"""
l = []
l.append("CoreDevOpsTools")
l.append("JIRA-Cloud")
res = []
for i in range(len(l)):
org = str(l[i])
after = ''
while True:
result = requests.post('https://api.github.com/graphql',
json={'query': Query.format(org,after)},
headers=headers)
json_data = json.loads(result.text)
if 'errors' in json_data:
print(json_data['errors'])
break
res_list = json_data['data']['organization']['auditLog']
for items in res_list['edges']:
res.append(items)
if not res_list['pageInfo']['hasNextPage']:
break
after = 'after: "%s"' % res_list['edges'][-1]['cursor']
time.sleep(1)
File "../AuditLog.py", line 98, in <module>
json={'query': Query.format(org,after)},
KeyError: '\n organization(login'
This is the structure of query in Insomnia/Postman.
query {
organization(login: "CoreDevOpsTools") {
auditLog(first: 100, after: "XYZ") {
edges {
node {
... on RepositoryAuditEntryData {
repository {
name
}
}
... on OrganizationAuditEntryData {
organizationResourcePath
organizationName
organizationUrl
}
... on TeamAuditEntryData {
teamName
}
... on TopicAuditEntryData {
topicName
}
... on OauthApplicationAuditEntryData {
oauthApplicationName
}
... on EnterpriseAuditEntryData {
enterpriseResourcePath
enterpriseUrl
enterpriseSlug
}
... on AuditEntry {
actorResourcePath
action
actorIp
actorLogin
operationType
createdAt
actorLocation {
countryCode
country
regionCode
region
city
}
#User 'Action' was performed on
userLogin
userResourcePath
userUrl
}
}
cursor
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
}
}
}
}
This is error I am getting, I am not able to figure out what is wrong. I looked at other same type of questions here but that didn't work either.
The issue with your code is that the string you're trying to format itself has curly brackets in places where you don't want to replace things. e.g the first line "query {"
You can fix this by doubling the curly brackets. So "{" becomes "{{" etc.
More on this here: stackoverflow.com

Multipart File upload in Ionic

I'm trying to upload a picture to my server with some additional data. My angularJs code is that:
function create_question(question, callback){
var form = new FormData()
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"processData": false,
"data": form
}
$cordovaFile.readAsDataURL(cordova.file.dataDirectory, question.name)
.then(function (success) {
form.append("file", success)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(Utf8Decode(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}
In my server, I have that view:
#parser_classes((MultiPartParser, ))
class CreateQuestion(APIView):
def post(self, request, format=None):
picture = request.data['file']
question_id = request.data['question_id']
project_id = request.data['project_id']
options = request.data['options']
title = request.data['title']
correct_option = request.data['correct_option']
username = request.user.username
project = Project.objects.get(project_id=project_id)
if project.owner_user.username == username:
ext = '.jpg'
aws = AWSClient()
picture_name = question_id + ext
picture_url = aws.put(picture, 'question_pictures', picture_name)
question = Question.objects.create(question_id=question_id, title=title,
picture_url=picture_url, options=options, owner_project=project,
correct_option=correct_option)
project.question_count += 1
project.picture_url = picture_url
project.save()
serializer = QuestionSerializer(question, context={"request": request})
return JsonResponse(serializer.data)
else:
return JsonResponse({"result": "fail"})
After I made the request, question was created and the picture file was uploaded to Amazon S3. However, I could not open the resulting file in my pc. Where am I doing mistake?
After a long search on the internet, I found the answer. First, I read file with
$cordovaFile.readAsArrayBuffer(directory,filename)
After that, I created a Blob object with the file:
var imgBlob = new Blob([success], { type: "image/jpeg" } );
My final angularJS code is:
function create_question(question, callback){
var form = new FormData()
$cordovaFile.readAsArrayBuffer(cordova.file.dataDirectory, question.name)
.then(function (success) {
var imgBlob = new Blob([success], { type: "image/jpeg" } );
form.append("file", imgBlob)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"filename": question.id,
"processData": false,
"data": form,
"file": success,
"filename": "file"
}
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(JSON.stringify(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}

Categories

Resources