Home > OS >  fetching data from outside API in Django
fetching data from outside API in Django

Time:09-22

I have an external API with its Content-Type, Authorization key, and tenant fields. The description of API is like this:

URL: https://url_address.com/
method: POST

Header:
    Content-Type:       application/json
    Authorization:      Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd=

Body: -> raw : 
    {
           "Tenant" : "devED"
    }

I try to fetch these data from my django views with this:

headers = {'Content-Type': 'application/json', 'Authorization': 'Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd='}
Body = { "Tenant": 'devED' }
GetAPI_response = requests.post('https://url_address.com/', headers=headers, params=Body).json()

But it says errors like:

{'Message': 'Request data is in Bad Format.'}

Please suggest how can I fix this?

CodePudding user response:

As of version 2.4.2, requests.post can be passed a json parameter that will be automatically encoded and will set the Content-Type header to application/json meaning you don't have to set it yourself

headers = {'Authorization': 'Basic xxxxxxxxxxxxxx'}
body = {'Tenant': 'devED'}
response = requests.post('https://url_address.com/', headers=headers, json=body)
  • Related