python requests post with bearer token

Python Requests POST with Bearer Token

As someone who has worked with APIs in Python, I have frequently used the Requests library to send HTTP requests to a server. When working with APIs that require authentication, such as those that use OAuth 2.0, it is common to use a bearer token to authenticate the requests.

To make a POST request with a bearer token in Python using the Requests library, you can do the following:

  1. Create a dictionary containing the headers for the request.
  2. Include the bearer token in the Authorization header of the dictionary.
  3. Create a dictionary containing the body of the request.
  4. Use the requests.post() method to send the request with the headers and body.

Code Example 1


import requests

url = "https://example.com/api/v1/items"

headers = {
    "Authorization": "Bearer xxxxxxxx"
}

payload = {
    "name": "New Item",
    "description": "This is a new item."
}

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

print(response.status_code)
    

In this example, we are sending a POST request to https://example.com/api/v1/items with a bearer token in the Authorization header. We are also including a JSON payload in the body of the request.

Code Example 2


import requests

url = "https://example.com/api/v1/items"

headers = {
    "Authorization": "Bearer xxxxxxxx"
}

data = {
    "name": "New Item",
    "description": "This is a new item."
}

response = requests.post(url, headers=headers, data=data)

print(response.status_code)
    

In this example, we are sending a POST request to https://example.com/api/v1/items with a bearer token in the Authorization header. We are also including a dictionary payload in the body of the request.