Python HTTP Requests
Python applications often communicate with web APIs using HTTP requests. The requests library provides a simple interface for sending HTTP requests and processing responses.
Install Requests
TEXT
Install the requests library with pip.
pip install requests
GET Request
Python
Send a GET request and read the response.
import requests
response = requests.get("https://example.com")
print(response.status_code)
print(response.text)
Query Parameters
Python
Send query parameters with a GET request.
import requests
params = {
"page": 1,
"limit": 10
}
response = requests.get("https://example.com/api/users", params=params)
print(response.url)
POST Request
Python
Send JSON data with a POST request.
import requests
payload = {
"name": "Alice",
"age": 25
}
response = requests.post(
"https://example.com/api/users",
json=payload
)
print(response.status_code)
Read JSON Response
Python
Convert a JSON response into Python data.
import requests
response = requests.get("https://example.com/api/users")
data = response.json()
print(data)
HTTP Headers
Python
Send custom HTTP headers.
import requests
headers = {
"Authorization": "Bearer TOKEN",
"Accept": "application/json"
}
response = requests.get(
"https://example.com/api/users",
headers=headers
)
Handle Request Errors
Python
Raise an exception for HTTP errors.
import requests
try:
response = requests.get("https://example.com/api/users", timeout=5)
response.raise_for_status()
print(response.json())
except requests.RequestException as error:
print("Request failed:", error)
Summary
The requests library makes HTTP communication simple in Python. You can send GET and POST requests, pass parameters and headers, process JSON responses, and handle network errors.