The Python Requests library is a popular HTTP client library that simplifies the process of making HTTP requests. It provides a user-friendly interface for sending HTTP/1.1 requests and handling responses.
To install the Requests library, use Python Package Management (pip):
pip install requests
Here's a simple example of how to use the Requests library to make a GET request:
import requests
response = requests.get('https://api.example.com/data')
print(response.status_code)
print(response.text)
The Requests library supports all common HTTP methods:
requests.get('https://api.example.com/data')
requests.post('https://api.example.com/submit', data={'key': 'value'})
requests.put('https://api.example.com/update', data={'key': 'new_value'})
requests.delete('https://api.example.com/remove')
Working with JSON data is straightforward:
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
print(data)
You can easily add custom headers to your requests:
headers = {'User-Agent': 'MyApp/1.0'}
response = requests.get('https://api.example.com/data', headers=headers)
The Requests library raises exceptions for network-related errors. Use Python Try...Except to handle these gracefully:
import requests
try:
response = requests.get('https://api.example.com/data')
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
For multiple requests to the same host, use a session to persist certain parameters:
with requests.Session() as session:
session.auth = ('user', 'pass')
response = session.get('https://api.example.com/protected')
The Python Requests library is an essential tool for web scraping, REST API interactions, and any task involving HTTP requests. Its simplicity and power make it a go-to choice for Python developers working with web services and APIs.