API Post Call response 500

Viewed 23

I am trying to make a post call to url and doing authorization within headers,I am certain that it is an error due to authorization. I am able to make post call successfully from postman. but when embedded in a python script it is throwing response 500.

below is the example of python post call :

url = "https://exampleurl"

headers = {
'Content-Type':'application/json',
'Accept':'application/json',
'Authorization':'rest_api_key=147EFE69551B4037B428D3743'
}

r = requests.post(url,data=payload, headers=headers)

Anyone seen this before?

1 Answers

You didn't show link to API documentation and you didn't show screenshot from Postman so I can only guess.


First:

Postman on right side should have icon </> to open function Code snippet which can generate code for different languages - even for Python (requests and http.client)

Screenshot from my answer Python : Passing form-data directly in fast-api with UI - Stack Overflow

enter image description here


Authorization in most APIs usually need only key or with Bearer

headers = {'Authorization': '147EFE69551B4037B428D3743'}

headers = {'Authorization': 'Bearer 147EFE69551B4037B428D3743'}

I see header 'Content-Type':'application/json'. If you have to send parameters as JSON then you should use json= instead of data=. And it will send it as {"name1": "value1", "name2": "value2", ...} . Using data= it sends it as name1=value1&name2=value2&...

And json= will also automatically add header 'Content-Type':'application/json' so you don't have to do it manually.

url = "https://httpbin.org/get"

headers = {
   'Accept': 'application/json',
   'Authorization': 'Bearer 147EFE69551B4037B428D3743'
}

payload = {
    "name1": "value1", 
    "name2": "value2",
}

response = requests.post(url, json=payload, headers=headers)
Related