0
votes

I'm a little bit new coding. I have an API that works perfectly sending the request from browser but when I try to run it with python requests it returns json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This is a part of my API:

post_data = json.loads(request.body.getvalue().decode('utf-8'))
run = postdata['run']
response = postdata['response']

and my requests with python is:

payload = {"run":1, "response" : "https://sampleserver"}
headers = {"content-type" : "application/json"}
r = requests.post("http://myserver", data = payload, headers = headers)

I think that maybe the problem is in the post_data

1
How are the two code snippets connected? You use requests.post() in the second. What is request.body in the first?quamrana
the request.body is defined in the run and response and I set this values in postman. The second is another python script. @quamranaggiiaaN0
I still don't get why you included the second snippet. The error occurs in the first. What has the second to do with that?quamrana
post_data = r.json()furas
error means that you didn't get JSON data. You should first display what you get in r.text (or request.body.getvalue()) to see you didn't get some HTML with explanation.furas

1 Answers

0
votes

You didn't show link to API documentation but I assume that you have to send data as JSON so you have to use json=payload instead of data=payload

And when you use json= then you don't have to add header "application/json" because it will add it automatically.

payload = {
    "run": 1, 
    "response" : "https://sampleserver",
}

r = requests.post("http://myserver", json=payload)

data= sends it as form data like run=1&response=http://myserver


BTW:

Next time when you get JSONDecodeError: then first check what you get request.body before you try to convert it to from JSON because error means that data is not correct JSON - and you should see data to see if you get JSON data, form data (run=1&response=..) or some HTML with warning or explanation.