Python Requests Package
The Python requests module allows you to send HTTP requests using Python. It is a popular package because it is simple to use, supports many HTTP request methods and is well-documented.
Installation
To install requests, you can use the pip package manager. Open a terminal or command prompt and run the following command:
pip install requests
Sending HTTP Requests
Once installed, you can start using requests to send HTTP requests. The most common HTTP request methods are:
- GET - retrieve data from a server
- POST - submit data to a server
- PUT - update data on a server
- DELETE - delete data from a server
To send an HTTP request with requests, you simply call the appropriate method and pass in the URL of the resource you want to interact with. For example:
import requests
response = requests.get('https://www.example.com')
print(response.text)
In this example, we are sending a GET request to the example.com website and printing out the response text.
Request Headers
You can add headers to your HTTP requests by passing in a dictionary of header key-value pairs to the headers parameter. For example:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get('https://www.example.com', headers=headers)
In this example, we are setting the User-Agent header to spoof the browser user agent string as if the request is coming from Chrome on Windows.
Request Parameters
You can add parameters to your HTTP requests by passing in a dictionary of parameter key-value pairs to the params parameter. For example:
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://www.example.com', params=params)
In this example, we are passing in two parameters to the GET request.
Request Body
You can add a body to your HTTP requests by passing in data to the data parameter in the form of a dictionary, list of tuples or a file object. For example:
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com', data=data)
In this example, we are sending a POST request with a body containing two key-value pairs.