The following code is an extract from Postman, where I am getting a response. For some reason the NodeJS version doesn't seem to be running and gives a "Socket hang up" error, where as the python version runs well. Both codes are pasted below:
const obj = {
asset: [
{
age: "33",
existingDisease: false,
gender: "MALE",
id: "883a8cb5446f4d6780db2e59bdf4ee35",
proposerRelationShip: "SELF",
used: false,
},
],
cover: [],
pinCode: "122001",
quoteId: "7637d7ff982145569fbfa604e3b74485",
sumInsured: "700000",
term: { unit: "YEAR", value: "1" },
};
const strObj = JSON.stringify(obj);
var options = {
method: "POST",
url: "https://sa.navi.com/v3/premium?paymentMode=SUBSCRIPTION",
headers: {
appversion: "2.2.4",
appversioncode: "92",
osversion: "Android_11",
deviceid: "3e44626c3bb37d4c",
defaultlocale: "en_US",
"x-session-token": "d635eb15-10aa-4315-9122-6ed3627dc1b8",
"x-click-stream-data":
'{"app":{"name":"Navi","version":"92","version_name":"2.2.4"},"device":{"device_id":"3e44626c3bb37d4c","advertising_id":"706649fa-50f0-410d-9c17-3085201808e2","manufacturer":"Google","model":"sdk_gphone_x86","os":"Android","os_version":"30"},"network":{"carrier":"Android","type":"Wifi"},"location":{"latitude":"37.4219983","longitude":"-122.084"},"user":{}}',
"x-target": "GI",
source: "APK",
"content-type": "application/json; charset=utf-8",
"content-length": "419",
"accept-encoding": "gzip",
"user-agent": "okhttp/4.9.0",
},
body: strObj,
};
console.log("Going to trigger API");
console.log(options);
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Gives error:
Error: Error: socket hang up
While the same code in Python works:
url = "https://sa.navi.com/v3/premium?paymentMode=SUBSCRIPTION"
payload = "{\"asset\":[{\"age\":\"33\",\"existingDisease\":false,\"gender\":\"MALE\",\"id\":\"883a8cb5446f4d6780db2e59bdf4ee35\",\"proposerRelationShip\":\"SELF\",\"used\":false}],\"cover\":[],\"pinCode\":\"122001\",\"quoteId\":\"7637d7ff982145569fbfa604e3b74485\",\"sumInsured\":\"700000\",\"term\":{\"unit\":\"YEAR\",\"value\":\"1\"}}"
headers = {
'appversion': '2.2.4',
'appversioncode': '92',
'osversion': 'Android_11',
'deviceid': '3e44626c3bb37d4c',
'defaultlocale': 'en_US',
'x-session-token': 'd635eb15-10aa-4315-9122-6ed3627dc1b8',
'x-click-stream-data': '{"app":{"name":"Navi","version":"92","version_name":"2.2.4"},"device":{"device_id":"3e44626c3bb37d4c","advertising_id":"706649fa-50f0-410d-9c17-3085201808e2","manufacturer":"Google","model":"sdk_gphone_x86","os":"Android","os_version":"30"},"network":{"carrier":"Android","type":"Wifi"},"location":{"latitude":"37.4219983","longitude":"-122.084"},"user":{}}',
'x-target': 'GI',
'source': 'APK',
'content-type': 'application/json; charset=UTF-8',
'content-length': '419',
'accept-encoding': 'gzip',
'user-agent': 'okhttp/4.9.0'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
Your content-length is wrong (you're passing 419, when the actual length of your payload JSON is 279). This probably means the receiving server is still waiting for the rest of the content to arrive, it never arrives so eventually the server times out and hangs up on you (thus why you get a hang up error).
And, lo and behold, when I just remove the content-length header and let the request library compute it automatically, the request starts working for me.
As for the python implementation, one guess is that it is overriding the wrong content-length and fixing it for you.
FYI, the request() library has been deprecated and it is not recommended that people write new code with it as it will not be advanced with new features in the future. A list of suggested alternatives (that all support promises) is here. My favorite in that list is got() which also supports most of the same options as the request() library, but is promise-based at is core and has a number of API improvements that make it easier to use (in my opinion).
And, indeed your code works just fine with the got() library (after removing the incorrect content-length header).
const got = require('got');
const obj = {
asset: [{
age: "33",
existingDisease: false,
gender: "MALE",
id: "883a8cb5446f4d6780db2e59bdf4ee35",
proposerRelationShip: "SELF",
used: false,
}, ],
cover: [],
pinCode: "122001",
quoteId: "7637d7ff982145569fbfa604e3b74485",
sumInsured: "700000",
term: { unit: "YEAR", value: "1" },
};
const strObj = JSON.stringify(obj);
var options = {
method: "POST",
url: "https://sa.navi.com/v3/premium?paymentMode=SUBSCRIPTION",
headers: {
appversion: "2.2.4",
appversioncode: "92",
osversion: "Android_11",
deviceid: "3e44626c3bb37d4c",
defaultlocale: "en_US",
"x-session-token": "d635eb15-10aa-4315-9122-6ed3627dc1b8",
"x-click-stream-data": '{"app":{"name":"Navi","version":"92","version_name":"2.2.4"},"device":{"device_id":"3e44626c3bb37d4c","advertising_id":"706649fa-50f0-410d-9c17-3085201808e2","manufacturer":"Google","model":"sdk_gphone_x86","os":"Android","os_version":"30"},"network":{"carrier":"Android","type":"Wifi"},"location":{"latitude":"37.4219983","longitude":"-122.084"},"user":{}}',
"x-target": "GI",
source: "APK",
"content-type": "application/json; charset=utf-8",
"accept-encoding": "gzip",
"user-agent": "okhttp/4.9.0",
},
body: strObj,
};
console.log("Going to trigger API");
got(options).then(response => {
console.log(response.body);
}).catch(e => {
console.log(e);
});
Related
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)
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.
I'm trying to convert my python code to flutter, but unable to do so. Trying to perform put request to update data on the website. Here is my original put request written in python.
import requests
url = "https://my.website.com/api/request/12"
headers = {"user_key":"kfrrt-000234-as12321-1h58dm66a"}
input_data = '''{
"request": {
"comment": "New comment",
"status": {
"request_status": "Open"
}
}
}'''
data = {'input_data': input_data}
response = requests.put(url,headers=headers,data=data,verify=False)
What I have so far in flutter :
postTaskInfo()async{
var jsonMP= {'request": {"comment": "New comment","status": {"request_status": "Open"}}'};
String jsonString= jsonEncode(jsonMP);
var url = 'https://my.website.com/api/request/12';
await http.put(url, body: jsonString, headers: {"user_key":"kfrrt-000234-as12321-1h58dm66a"} ).then((response){
setState(() {
print(response.body);
});
});
}
I get an error " Unhandled Exception: Converting object to an encodable object failed: Instance of '_CompactLinkedHashSet
Thank you !
The problem occurs due to jsonEncoding failed to encode non-json data to string, so correct the jsonMP variable.
yours:
var jsonMP= {'request": {"comment": "New comment","status": {"request_status": "Open"}}'};
Should be in the form of
var jsonMP = {
"request": {
"comment": "New comment",
"status": {"request_status": "Open"}
}
};
I'm trying to hit my geocoding server's REST API:
[https://locator.stanford.edu/arcgis/rest/services/geocode/USA_StreetAddress/GeocodeServer] (ArcGIS Server 10.6.1)
...using the POST method (which, BTW, could use an example or two, there only seems to be this VERY brief "note" on WHEN to use POST, not HOW: https://developers.arcgis.com/rest/geocode/api-reference/geocoding-geocode-addresses.htm#ESRI_SECTION1_351DE4FD98FE44958C8194EC5A7BEF7D).
I'm trying to use requests.post(), and I think I've managed to get the token accepted, etc..., but I keep getting a 400 error.
Based upon previous experience, this means something about the formatting of the data is bad, but I've cut-&-pasted directly from the Esri support site, this test pair.
# import the requests library
import requests
# Multiple address records
addresses={
"records": [
{
"attributes": {
"OBJECTID": 1,
"Street": "380 New York St.",
"City": "Redlands",
"Region": "CA",
"ZIP": "92373"
}
},
{
"attributes": {
"OBJECTID": 2,
"Street": "1 World Way",
"City": "Los Angeles",
"Region": "CA",
"ZIP": "90045"
}
}
]
}
# Parameters
# Geocoder endpoint
URL = 'https://locator.stanford.edu/arcgis/rest/services/geocode/USA_StreetAddress/GeocodeServer/geocodeAddresses?'
# token from locator.stanford.edu/arcgis/tokens
mytoken = <GeneratedToken>
# output spatial reference id
outsrid = 4326
# output format
format = 'pjson'
# params data to be sent to api
params ={'outSR':outsrid,'f':format,'token':mytoken}
# Use POST to batch geocode
r = requests.post(url=URL, data=addresses, params=params)
print(r.json())
print(r.text)
Here's what I consistently get:
{'error': {'code': 400, 'message': 'Unable to complete operation.', 'details': []}}
I had to play around with this for longer than I'd like to admit, but the trick (I guess) is to use the correct request header and convert the raw addresses to a JSON string using json.dumps().
import requests
import json
url = 'http://sampleserver6.arcgisonline.com/arcgis/rest/services/Locators/SanDiego/GeocodeServer/geocodeAddresses'
headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
addresses = json.dumps({ 'records': [{ 'attributes': { 'OBJECTID': 1, 'SingleLine': '2920 Zoo Dr' }}] })
r = requests.post(url, headers = headers, data = { 'addresses': addresses, 'f':'json'})
print(r.text)
I am using the fetch library from reactjs for getting and pushing data to/from my flask API. But can't get the desired response from the my api.
This is my flask api:
#app.route('/adduser',methods=['POST'])
def indx():
data=request.get_json(force=True)
email=request.get_json()["email"]
password=request.get_json()['password']
try:
auth.create_user_with_email_and_password(email,password)
except:
userexists="User Already Exists"
try:
user=auth.sign_in_with_email_and_password(email,password)
id = auth.get_account_info(user['idToken'])
db.child("users").push(id)
except:
invalidCredentials="Wrong Credentials"
if request.get_json(force=True):
x={
"name":"sarmad",
"roll":"052"
}
s=json.dumps(x)
return s
else:
return ""
This is react js code:
fetch('http://127.0.0.1:5000/adduser', {
mode:'no-cors',
method: 'POST',
headers: {
'Accept': 'application/json',
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json'
},
body: JSON.stringify({
'email': this.state.email,
password: this.state.password,
name: this.state.name,
// userType: userTy,
dob:this.state.DOB,
address:this.state.Address,
gender:'male',
phone:'090078601',
// roles:roles
})
}).then((response) => response).then((responseJson) => {
console.log(responseJson);
//this.setState({pressed: false});
})
I need to receive the data passed back from the Flask API either as a string or json. This is my current response back:
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 0 statusText: "" type: "opaque" url: "" _proto_: Response
Any help would be greatly appreciated!
Just do it with .json()
}).then((response) => response.json()).then((responseJson) => {
console.log(responseJson);
//this.setState({pressed: false});
})