How to Use Python Requests
As someone who has worked with Python for a few years now, I can tell you that the requests library is one of the most useful tools to have at your disposal. It makes sending HTTP requests a breeze and can be used for a wide variety of tasks such as web scraping, API requests, and more. Here's a brief overview of how to use Python requests:
Installation
Before you can start using Requests, you'll need to install it. You can do this using pip, the Python package manager:
pip install requests
GET Requests
The most common type of request is a GET request, which retrieves data from a server. Here's an example:
import requests
response = requests.get('https://www.example.com')
print(response.text)
- The requests library is imported.
- A GET request is made to 'https://www.example.com'.
- The response is stored in the 'response' variable.
- The response text is printed.
POST Requests
POST requests are used to send data to a server. Here's an example:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com/post', data=payload)
print(response.text)
- The requests library is imported.
- A dictionary 'payload' is created with the data to be sent.
- A POST request is made to 'https://www.example.com/post' with the data from the 'payload' dictionary.
- The response is stored in the 'response' variable.
- The response text is printed.
Headers
You can add headers to your requests by passing a dictionary to the 'headers' parameter:
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://www.example.com', headers=headers)
print(response.text)
- The requests library is imported.
- A dictionary 'headers' is created with the User-Agent header set to Mozilla/5.0.
- A GET request is made to 'https://www.example.com' with the headers from the 'headers' dictionary.
- The response is stored in the 'response' variable.
- The response text is printed.
Authentication
If you need to authenticate your requests, you can do so by passing your credentials to the 'auth' parameter:
import requests
response = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print(response.json())
- The requests library is imported.
- A GET request is made to 'https://api.github.com/user' with the authentication details passed to the 'auth' parameter.
- The response is stored in the 'response' variable.
- The response JSON is printed.