GitHub GraphQL API Problems parsing JSON - python

What is wrong here?
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query+'\"}',headers=headers)
print (r2.json())
I've got
{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}
but this snippet of code below works correctly
query1= '''{ viewer { login name } }'''
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query1+'\"}',headers=headers)
print (r2.json())
I've tried out to change quotes (from " into ' or with " and so on) but it doesn't work.

The problem is related with the double quotes (").
On the first snippet, when you join the '{"query": \"'+query+'\"}' with the query variable, you get the following result:
{"query": "{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }"}
Notice how the double quote from "ALEXSSS" are not escaped, therefore the resultant string is not a json valid format.
When you run the second snippet, the resultant string is:
{"query": "{ viewer { login name } }"}
which is a valid json string.
The easiest and best solution is simply use the JSON library instead of trying to do it manually, so you won't need to worry about escaping characters.
import json
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', json.dumps({"query": query}), headers=headers)
print (r2.json())
But remember that you could also just escape the characters on the query manually:
query='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": "'+query1+'"}', headers=headers)
print (r2.json())
it works as expected :)

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 to fill ACF fields using Wordpress Rest-Api in Python

I'm trying to fill ACF Fields using Wordpress Rest-Api in Python, but when I try to make request it's giving "400 Bad Request". I'm using ACF latest verison 5.11 that comes with in-built api integration.
This is my code, please help me to solve this problem.
import requests
import json
import base64
url = "example.com/wp-json/wp/v2/posts"
user = "exmaple#gmail.com"
password = "RIHr O7kE SCn0 LXVW xyPc jBn9"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
post = {
"title" : "Hello World",
"type" : "post",
"status" : "publish",
"content" : "This is my first post created using rest API",
"acf" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
}
responce = requests.post(url , headers=header, json=post)
print(responce.status_code, responce.reason)
Three things to check/change here
In your functions.php file in WordPress, ensure you've registered the post meta. For example
function function_name() {
register_meta('post', 'youtube_url',
[
'object_subtype' => 'post',
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
}
]
);
}
add_action( 'rest_api_init', 'function_name' );
2 then update...
"acf" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
to...
"meta" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
3 And finally, in the field group settings in ACF, ensure 'Show in REST API' is selected

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)

how to send parameters to databricks notebook?

I triggering databricks notebook using the following code:
TOKEN = "xxxxxxxxxxxxxxxxxxxx"
headers = {"Authorization": "Bearer %s" % TOKEN}
data = {
"job_id": xx,
"notebook_task": {
"base_parameters": {
"param1":"key1",
"param2": "key2",
}
},
}
resp = requests.post(
"https://xxxxxx.cloud.databricks.com/api/2.0/jobs/run-now",
headers=headers,
data=json.dumps(data),
)
when i try to access it using dbutils.widgets.get("param1"), im getting the following error:
com.databricks.dbutils_v1.InputWidgetNotDefined: No input widget named param1
I tried using notebook_params also, resulting in the same error.
base_parameters is used only when you create a job. When you trigger it with run-now, you need to specify parameters as notebook_params object (doc), so your code should be :
data = {
"job_id": xx,
"notebook_params": {
"param1":"key1",
"param2": "key2",
},
}

How do I stop removing double quotes after passing command-line argument?

Hi I'm trying to pass json in terminal as a payload input but after passing argument in terminal I got json without double quotes, I want to have my response output in json format as well.
How do I stop removing double quotes after passing command-line argument?
Here is my code,
def get_apicall():
Token = get_token()
url = "http://localhost.../resp"
Header = {'Content-Type': "application/json", 'Authorization': 'Bearer ' + str(Token)}
payload = sys.argv[1]
print(payload)
payload1 = json.dumps(payload )
print(payload1)
response = requests.request("POST", url, data=payload1, headers=Header)
print(response.text)
get_endpoint()
My input json is { "request":"success","input":[ { "type":" ", "content":[ { "type":" ", "meta":{ "sample_type":" " , deatail":" "} ] } ], "output":[ { "type":" ","content":[ { "type":"", "meta":{ "sample_type":"", }, "deatils":" " } ] } ] }
When I'm trying to print input payload which I passed in teminal payload = sys.argv[1] print(payload)
but I got this when I did print(payload) which removed double qoutes : { request:success,input:[ { type: , content:[ { type: , meta:{ sample_type: , deatail: } ] } ], output:[ { type: ,content:[ { type:, meta:{ sample_type:, }, deatils: } ] } ] }
please correct me if I'm wrong some where in my above code.
I want to have print(payload) same as my input payload
{ "request":"success","input":[ { "type":" ", "content":[ { "type":" ", "meta":{ "sample_type":" " , deatail":" "} ] } ], "output":[ { "type":" ","content":[ { "type":"", "meta":{ "sample_type":"", }, "deatils":" " } ] } ] }`
Using the print() function can apply different formatting for printing. Maybe try using repr() function which will show the object based on the way Python is interpreting it. I.e. it will include type information like quotes for strings, square brackets for lists, and curly braces for dictionaries.
You're trying to print JSON using print(), which formats JSON (removes double quotes).
If you want to keep the quotes in the output, use json.dumps() (docs) in print() instead. That is, just replace print(payload) with print(json.dumps(payload)) in your code.
So, the following code will work for you:
import json
print(json.dumps(payload))

Categories

Resources