requests headers example

Requests Headers Example

When making HTTP requests, headers are often used to provide additional information about the request being made. Headers can be used to specify things like the content type of the request, the language being used, and more. Here's an example of some headers that might be included in a request:


import requests

url = "https://www.example.com"
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36",
    "Accept-Language": "en-US,en;q=0.9",
    "Referer": "https://www.google.com/",
    "Cookie": "session_id=abc123",
}

response = requests.get(url, headers=headers)

User-Agent Header

The User-Agent header is used to identify the client making the request. This can be useful for servers to know what kind of device or browser is being used to access their content. In this example, we're using a User-Agent string that indicates that we're using Chrome on a Mac.

Accept-Language Header

The Accept-Language header is used to indicate what languages the client is able to understand. This can be useful for servers to know what language to serve their content in. In this example, we're indicating that we prefer English, but will accept other languages with a lower priority.

Referer Header

The Referer header is used to indicate the URL of the page that linked to the current page. This can be useful for servers to know how users are finding their content. In this example, we're indicating that we came from a Google search.

The Cookie header is used to send cookies along with the request. Cookies are small pieces of data that are stored on the user's computer and can be used to remember information about the user's session. In this example, we're sending a session ID cookie along with the request.

These are just a few examples of the many headers that can be included in an HTTP request. It's important to read the documentation for any APIs or servers you're interacting with to determine what headers are required or recommended.