Home > Back-end >  How to get API answer with an API key using the requests package in Python
How to get API answer with an API key using the requests package in Python

Time:10-28

How to get http request from API organized around REST, JSON is returned by all API responses. All ressources have support for bulk fetches via "list" API methods

Here is what I have as documentation:

# With shell, you can just pass the correct header with each request
curl "https://www.api_url.com/api/dispute?page=1&limit=5"
  -H "Authorization: [api_key]"

# Query Parameters:
# page  1   The cursor used in the pagination (optional)
#limit  10  A limit on the number of dispute object to be returned, between 1 and 100 (optional).

I don't know how to interpret this in python and to pass api_key to extract the data from this object dispute

import requests
import json
response = requests.get("https://api_url.com/")

CodePudding user response:

You can use the enter image description here

For the provided curl input:

curl "https://www.api_url.com/api/dispute?page=1&limit=5" \
  -H "Authorization: [api_key]"

Here is the result in Python. Note that I've changed params to a dict object, as it's easier to work with dictionaries in Python. It doesn't matter if the values for any of the query params are a type other than str, as they will simply be concatenated in the URL string when making the request.

import requests

headers = {
    'Authorization': '[api_key]',
}

params = {
    'page': 1,
    'limit': 5
}

response = requests.get('https://www.api_url.com/api/dispute',
                        headers=headers, params=params)

CodePudding user response:

The -H option in curl sets a header for the request.

For a request using requests, you can set extra headers by passing a keyword argument headers.

import requests
import json

response = requests.get(
  "https://www.api_url.com/api/dispute",
  headers={"Authorization" : "<api_key_here>"}
)

You can also add your parameters easily if needed

response = requests.get(
  "https://www.api_url.com/api/dispute",
  headers={"Authorization" : "<api_key_here>"},
  params={
    "page": 1,
    "limit":1
  }
)

If you want to make multiple requests, you can look into using a requests.Session. Session Tutorial

It will allow you to set the header centrally.

You can also use an Auth Handler to manage authentication.

  • Related