jeppoo1
jeppoo1

Reputation: 698

POST requests API using Python - status code 500

I am writing a script in Python (3.7.4, Windows 10) for a POST request (REST API), the object is to retrieve data from another database and move it to another.

from os import getenv
import requests

# header includes login credentials and content type
header = {'access_key': "key", "access_token": getenv("token1"), 'content-type': 'application/json'}

# Body includes table names and other specified data to retrieve
body = {
# table names etc.
}

# Post request and printing of the post request text
post_r = requests.post(url = POST_url, data = body, headers = header)
post_text = post_r.text
print(post_text)

This throws me an HTTP Error status code 500. What should I change in my code for it to print the post_text correctly?

Upvotes: 0

Views: 504

Answers (1)

jeppoo1
jeppoo1

Reputation: 698

I figured out the solution:

post_r = requests.post(url = POST_url, data = body, headers = header)

should be changed to

post_r = requests.post(url = POST_url, json = body, headers = header)

So, I just replaced data with json and the script printed me the post_text output just fine.

It did not help to change the 'content-type' in header to 'application'. It threw me status code 415 ("HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format. The format problem might be due to the request's indicated Content-Type or Content-Encoding , or as a result of inspecting the data directly.").

I still wonder why data = body is not acceptable in the post request row.

Upvotes: 1

Related Questions