Python requests

Can we consume an API, for example use the POST method to retrieve products. Note that we pass the security key in the body or data. it's possible ??

def api(request):
url = 'https://datausa.io/api/data?product'

x = requests.post(url,data={'securityKey':'valueKey')
contenu=x.text
return HttpResponse(contenu)

Of course !

Most people use the requests library because it removes a lot of boilerplate and it is a really well built and maintained library : https://requests.readthedocs.io/en/latest/

It is as easy as doing that :

r = requests.get('https://datausa.io/api/data?product')
r.status_code
200
r.headers = {'security-key': 'valuekey'}

You can also use Django Rest Framework with the authentification mechanism so you can use token to consume your api : https://www.django-rest-framework.org/api-guide/authentication/

J'ai une erreur HTTP 415 Voici le code

def api(request):
url = 'http://api-content/product/GetProduct'

x = requests.post(url, headers = {'security-key': 'valu-key'})
content=x.status_code
return HttpResponse(content)

The idea is to use the POST method by passing it a security key in the headers to simply retrieve the product data I have an http 400 error here is the code

def api(request):
  headers={'content-type':'application/json','security-key':'value-key'} 
  url = 'http://api-content/product/GetProduct'

  x = requests.post(url, headers = headers)
  content=x.status_code
  return HttpResponse(content)
Back to Top