I'm working on an API for my application to send a POST request to an external API. So for example, if my app hits endpoint /myapp/api I want it to call out to an external API and grab some data. In this case, I need this to be a POST request because in order to get the data that I want, I need to pass in some values.
I have made this POST call directly to the external API via Postman successfully many times, and I'm now trying to reproduce that in my python code.
In my views.py, I have this:
class MyAPPViews(APIView):
def post(self,request):
crt = 'path/to/crtfile'
key = 'path/to/keyfile'
#here I tried to reproduce the headers from the postman call
#as best as I could just to be extra specific
headers = {
'Content-Type': 'application/json',
'Accept': '/*/',
'Accept-Encoding': 'gzip,deflate,br',
'Connection': 'keep-alive'
}
payload = {
"unitList": [
"CFQU319303"
]
}
res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key))
print('this is the true http resonse: ',res.status_code)
data = res.json()
return Response({"status": "success", "data": data})
in my urls.py I have this
path('externalAPI',MyAPPViews.as_view()),
Now, when I try to go into postman and hit http://127.0.0.1:8000/myapp/externalAPI
I get a 500 status code returned and the JSONDecodeError of Expecting value: line 1 column 1 (char 0). I understand that this means that basically the json response was empty and there was nothing for it to parse.
Is there anything blatantly wrong with my views.py code?
EDIT Within the res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key)), I had to change data=payload to data=json.dumps(payload). I'm assuming it didn't like the way I formatted my payload initially. After that, I also deleted everything but the Content-Type: application/json out my headers dictionary.