What is the Python Request Library?
Requests Library is a popular Library that makes it easy to send HTTP requests using POST, GET and DELETE methods, upload files, post JSON and XML data, and submit HTML forms. The Requests Library automatically validates server SSL certificates and supports International Domain Names and session cookies. The Requests Library is based on the urllib3 library and hides the complexity of making HTTP requests behind a simple API. Although the Requests Library is not included in the Python distribution, almost everyone uses Requests Library because the Python code for working with HTTP becomes short, simple, and straightforward.
What are HTTP Headers?
HTTP headers allow clients to send additional information to the server and enable the server to provide additional information to clients, such as the data type and size in the POST content. HTTP headers are invisible to the end-user and are only visible to clients, servers, and network administrators. Custom HTTP headers are used to provide additional information related to the current request or response for troubleshooting purposes. HTTP headers include a case-insensitive name followed by a colon ":" and its value. Spaces before the value are ignored.
An example of HTTP headers when sending a POST request to the server:
How to install the Python Requests Library?
You can install the Requests Library using the pip package installer for Python.
After installing the Requests Library, you can use it in your code by importing the Requests Library with the following Python code:
Passing HTTP Headers to Requests Library methods
You can pass HTTP headers to the Requests library methods as the second argument to the requests.get(), post(), put(), patch(), and delete() methods:
Where:
- URL: target URL endpoint.
- headers: a list of HTTP Headers to send to the server.
Request Library methods do not change their behavior regardless of the custom headers you send. Custom headers are passed in the final request and have lower priority than standard headers:
Example of sending additional HTTP Headers in Python
An example of sending a request with custom HTTP headers to the ReqBin echo URL:
How to read response headers using Python requests library?
The Python Requests Library stores the server's response HTTP headers as a Python dictionary in the response.headers object. You can work with headers object as you would with a regular Python dictionary. For example, you can access a header by name or check for the existence of a header using the in operator:
The server can send the same header multiple times with different values. The Request Library combines such headers into a single comma-separated header, per RFC 7230.