Last modified: Jul 03, 2023 By Alexander Williams

How to Send Requests with Headers and Data in Python

In this guide, we'll learn how to send a request with data and headers using the requests library.

What are HTTP request headers

headers refer to additional information included in the request or response messages. Such as the content type, authentication credentials, caching directives, etc.

headers={'Accept': 'application/vnd.github.v3.text-match+json'}

How to use headers with requests

You can easily use headers with requests by passing a dictionary to the headers parameter of the requests.post() function.

Here is an example:

import requests

# URL of the endpoint to send the POST request
url = 'https://example.com/post-endpoint'

# Custom headers to include in the request
headers = {
    'Content-Type': 'application/json',  # Specify the content type as JSON
    'Authorization': 'Bearer your-token',  # Include authorization token
    'User-Agent': 'Your User Agent'  # Set the user agent for the request
}

# Data to include in the request body (payload)
data = {
    'key1': 'value1',
    'key2': 'value2'
}

# Send a POST request with the specified headers and data
response = requests.post(url, headers=headers, json=data)

As you can see, we've included custom headers in the request. You can add as many headers as needed, and the keys and values depend on the specific requirements of the API or server you are interacting with.