How to set the accept header in an HTTP request in Python?

Published on Aug. 22, 2023, 12:18 p.m.

To set the Accept header in an HTTP request in Python, you can use the requests library. The Accept header specifies the media types that the client can handle in the response. Here is an example code snippet that demonstrates how to set the Accept header:

import requests

url = 'https://www.example.com/api/data'
headers = {'Accept': 'application/json'}
response = requests.get(url, headers=headers)

# Process the response data

In this example, we create a dictionary object called headers that contains the Accept header with the value application/json, which indicates that the client accepts JSON-encoded data in the response. Then we pass this header as an argument to the get() method of the requests library.

You can modify the value of the Accept header to suit your desired media type. You can also set other headers as required using the headers dictionary object.

Tags: