HTTP Post Python - json

please help to resolve the issue, I sent payload, but get error 400:
Post:
payload = {"country_code":"XX","phone_number":"1234567890"}
r = requests.post("https://site.su/jwt-auth/start", params=payload, headers=headers, verify=False)
r.json()
{'statusCode': 400,
'reason': 'invalid_request',
'errorId': 'c2114dc8-0632-49c6-8cfb-cc5b08897ecc',
'message': 'Validation failed: \n -- PhoneNumber: phone_number is reuiqred Severity: Error',
'localizedMessage': 'One of parameter was sent with an error. Please try again or go back to the previous page.',
'invalidParameters': {'phone_number': {'reason': 'NotEmptyValidator',
'localizedMessage': 'phone_number is required'}}}
Content-Disposition: form-data; name="cd[formFeatures]"
[{"id":"","name":"country_code","tag":"input","inputType":"text"},{"id":"","name":"","tag":"input","inputType":"text","valueMeaning":"empty"},{"id":"","name":"phone_number","tag":"input","placeholder":"+7 (___) ___-__-__","inputType":"tel"}]
Payload
I have provided my code.

Related

API request works in browser, but, doesn't work in postman or python requests module

I am trying to request this API: https://iso19139echnap.geocat.live/geonetwork/srv/api/0.1/groups/11864
it works in browser if I enter it as a direct URL. But it doesn't work in Python Request module or in Post man.
Python code looks like the following:
import requests
payload = {
'username': 'corey',
'password': 'testing'
}
r = requests.get('https://iso19139echnap.geocat.live/geonetwork/srv/api/0.1/groups/11864')
print(r)
--------------------------------------------------------
returns
<Response [400]>
import requests
url = "https://iso19139echnap.geocat.live/geonetwork/srv/api/0.1/groups/11864"
payload = {}
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-IE,en-GB;q=0.9,en-US;q=0.8,en;q=0.7',
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
you have to add accept encoding header
Add the same in postman also and it works fine

415 error when sending data to a server

I am building an app using ionic/cordova that will take a scan, store this to the device (this part works), and also upload this data to a server (this part doesn't work).
The server is a RESTful api that expects JSON to be POSTed (I didn't create the server, these are the details I have been given).
When I try to post to the server I am getting the following error -
{status: 415, url: "http://jsfitnessservice.azurewebsites.net/api/values123", headers: {…}, error: ""} error:""
headers:
content-length:"0"
date:"Tue, 06 Feb 2018 19:41:36 GMT"
request-context:"appId=cid-v1:bf5436d9-7e1e-491e-b79d-d40d9b401307"
server:"Kestrel"
x-android-received-millis:"1517946100312"
x-android-response-source:"NETWORK 415"
x-android-selected-protocol:"http/1.1"
x-android-sent-millis:"1517946100070"
x-powered-by:"ASP.NET"
My code -
let httpData = {
"id": this.device.uuid,
"scanDateTimes": this.lastScans,
"appVersion": "Version 1.0"
}
let header = new Headers();
header.append('Content-Type', 'application/json; charset=utf-8');
this.http.post('http://jsfitnessservice.azurewebsites.net/api/values 123', httpData, header).then
(data =>{
console.log("Data Status - ", data.status);
}).catch(error =>{
console.log("Error - ", error)
});
I have tried a few things that I have seen online, such as adding the header to an object, or using JSON.Stringify() around the data I am sending. But these give errors too.
JSON.stringify around data gives this error -
status: -1, error: "unsupported params type, needs to be a JSON object"
Making header an object gives this error -
status: 0, error: "advanced-http: header values must be strings", headers: {…}}
Have you tried using
this.http.setDataSerializer(‘json’)
this.http.post('http://jsfitnessservice.azurewebsites.net/api/values 123', httpData, {'Content-Type': 'application/json; charset=utf-8'}).then
(data =>{
console.log("Data Status - ", data.status);
}).catch(error =>{
console.log("Error - ", error)
});

Python 3.x - Web Server - extract json body from POST request

I am sending a Post request with a json body to a server but can not extract the json file when it arrives. I have does exhaustive searches but to no avail. I have provided both client and server scripts to illustrate what is happening.
All I need is to extract the json portion at the end of the received string so I can analyze the request and return the appropriate data.
I'm sure it's simple but I can't seem to find the answer. Any direction would be appreciated
***
CLIENT: script to test Server
import json
import requests
def info_send():
url = 'http:1234abcd.ngrok.io'
payload = {
'command': '["command", "status", "off", None]',
'userID': 'userID string',
'status': 'current status',
}
requests.post(url, data=json.dumps(payload))
info_send()
***
SERVER: receives json POST request
HOST, PORT = '', 5000
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Listening on port %s' % PORT)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024).decode('utf-8')
print(request)
***
This is what is printed at the server
POST / HTTP/1.1
Host: 1234abcd.ngrok.io
User-Agent: python-requests/2.18.4
Accept-Encoding: gzip, deflate
Accept: /
Content-Length: 112
X-Forwarded-For: 112.162.214.265
{"command": "[\"command\", \"status\", \"off\", None]", "userID": "userID string", "deviceID": "current status"}

Requests module JSONDecodeError

I have the following code to post using requests module
api_path = r'/DeviceCategory/create'
api_server = (self.base_url + api_path)
logging.info("Triggered API : %s", api_server)
arguments = {"name": "WrongTurn", "vendor": "Cupola", "protocolType": "LWM2M"}
headers = {'content-type': 'application/json;charset=utf-8', 'Accept': '*'}
test_response = requests.post(api_server,headers=headers,cookies=self.jessionid,
timeout=30, json=arguments)
logging.info(test_response.headers)
logging.info(test_response.request)
logging.info(test_response.json())
logging.info(test_response.url)
logging.info(test_response.reason)
The following response i got in header
2017-08-22 12:03:12,811 - INFO - {'Server': 'Apache-Coyote/1.1', 'X-FRAME-OPTIONS': 'SAMEORIGIN, SAMEORIGIN', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, DELETE, PUT', 'Access-Control-Allow-Headers': 'Content-Type', 'Content-Type': 'text/html;charset=utf-8', 'Content-Language': 'en', 'Transfer-Encoding': 'chunked', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Date': 'Tue, 22 Aug 2017 06:33:12 GMT', 'Connection': 'close'}
And JSON decoding the error
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Can some please help me out, the status code i got is 500
It means that the server didn't return any response values (there was no response body, so json() couldn't decode the JSON). Given the 500 error, that probably means that your API call was bad. Not being familiar with the API, I cannot say more but my guess is that you are passing the arguments wrong, try something like:
test_response = requests.post(api_server,headers=headers,cookies=self.jessionid,
timeout=30, data=arguments)

Parsing html/text return type to be able to see the content with AFNetworking

I am constrained to using AFNetworking, but I am working in Swift. I am trying to retrieve data from a POST API request that is supposed to be returning JSON. However it seems that no matter how I make the request I am not able to see what is being returned and that it does not seem to be in proper JSON format. Here's what I've tried.
(1) The canonical approach:
manager.responseSerializer = AFJSONResponseSerializer.init(readingOptions: .AllowFragments)
manager.responseSerializer.acceptableContentTypes = serialiazationTypes
This produces the error: Invalid value around character 2
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 2." UserInfo={NSDebugDescription=Invalid value around character 2., NSUnderlyingError=0x60800004ad70 {Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x608000a2c140> { URL: https://API_ADDRESS} { status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2261;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 07 Dec 2016 15:46:26 GMT";
Server = "nginx/1.10.1";
} },
(2) Using the standard parser. So basically I removed any explicit setting of the response serializer, which produced this error:
Optional(Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo={NSUnderlyingError=0x60000004ace0 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x61800082e6a0> { URL: https://API_ADDRESS } { status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2261;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 07 Dec 2016 15:49:12 GMT";
Server = "nginx/1.10.1";
(3) So then I tried to read as text/html, not requiring JSON, so that I could see what the problem is, but I don't seem to be able to retrieve this and just see what the content is either. So with this code:
manager.responseSerializer = AFHTTPResponseSerializer()
I ended up with this response, which does not even indicate why this is a bad request:
"Request failed: bad request (400)"
{ status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2261;
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 07 Dec 2016 15:51:10 GMT";
Server = "nginx/1.10.1";
} }
Here are my questions
(1) In cases 1 & 2 above are these problems with parsing the response code whereas in case 3 I am just seeing the server tell me that my request is bad?
(2) How can I start figuring out why my request is bad? This is an internal API, but I'm not getting a lot of help with how it works. I have a sample curl command that does work with the API, but I'm not clear on how I am departing from it:
curl -X POST -v -s -H "Session-Token: EYYW$YW$YWYW" -H "Content-type: application/json" -d#sample.json https://API_ADDRESS
What is different between that and what I am doing below:
manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFHTTPResponseSerializer()
manager.requestSerializer.setValue(sessionToken, forHTTPHeaderField: tokenString)
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-type")
manager.POST(
user_url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation?,
responseObject: AnyObject!) in
print("JSON FROM POST: \(responseObject)")
},
failure: { (operation: AFHTTPRequestOperation?, error: NSError?) in
print("there was an error in POST: \(error)")
}
)