The requests library in Python simplifies the process of sending HTTP requests and handling responses. It supports various HTTP methods like GET, POST, PUT, DELETE, and more. Below are some code snippets demonstrating how to access APIs, send requests, and handle responses using the requests library.
1. Basic GET Request
A simple GET request to fetch data from an API.
import requests# Make a GET request to an APIresponse = requests.get("https://api.github.com")# Check if the request was successfulif response.status_code ==200:print("Response Status Code:", response.status_code)print("Response Body:", response.json())# Get the response as JSONelse:print(f"Failed to retrieve data. Status code: {response.status_code}")
2. GET Request with Query Parameters
Adding query parameters to a GET request.
import requests# Define the API endpoint and parametersurl ="https://api.openweathermap.org/data/2.5/weather"params ={'q':'London','appid':'your_api_key_here'# Replace with your actual API key}# Make a GET request with parametersresponse = requests.get(url,params=params)# Check if the request was successfulif response.status_code ==200:print("Weather data:", response.json())else:print("Failed to retrieve weather data:", response.status_code)
3. POST Request
Sending data with a POST request to an API.
4. Handling Response JSON
Accessing and processing JSON data from a response.
5. Error Handling in Requests
Handling different HTTP status codes and errors.
6. Sending Headers with Requests
Adding custom headers to a request.
7. Handling Cookies in Requests
Sending and receiving cookies with requests.
8. Timeouts in Requests
Setting a timeout for requests to avoid long waits.
9. File Upload with Requests
Uploading a file using a POST request.
10. Session Object for Persistent Connections
Using a session object to persist certain parameters across multiple requests.
Summary of Key Points:
GET: To fetch data from an API.
POST: To send data to an API.
Error Handling: Use try-except to manage errors and unexpected responses.
Headers: Add custom headers to requests.
Cookies: Manage cookies with cookies argument in requests.
Timeouts: Set timeouts for requests using the timeout parameter.
Session: Use requests.Session() to maintain persistent connections.
File Upload: Upload files using the files argument in POST requests.
These examples cover basic usage, error handling, authentication, and working with cookies and sessions, providing a comprehensive guide to interacting with APIs using the requests library.
import requests
# Define the API endpoint
url = "https://httpbin.org/post"
# Data to be sent with the POST request
data = {
'name': 'John Doe',
'age': 30
}
# Make a POST request
response = requests.post(url, json=data)
# Check if the request was successful
if response.status_code == 200:
print("Response:", response.json())
else:
print("Failed to post data:", response.status_code)
import requests
# Define the API endpoint
url = "https://api.github.com/repos/psf/requests"
# Make a GET request
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
data = response.json() # Parse the JSON response
print("Repository Name:", data['name'])
print("Stars:", data['stargazers_count'])
else:
print("Failed to fetch data:", response.status_code)
import requests
# Define the API endpoint
url = "https://jsonplaceholder.typicode.com/posts/1"
# Make a GET request
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for bad HTTP status codes (4xx, 5xx)
print("Response:", response.json())
except requests.exceptions.HTTPError as errh:
print(f"HTTP error occurred: {errh}")
except requests.exceptions.RequestException as err:
print(f"Error occurred: {err}")
import requests
# Define the API endpoint
url = "https://httpbin.org/headers"
# Custom headers
headers = {
'User-Agent': 'my-app/1.0',
'Authorization': 'Bearer your_token_here'
}
# Make a GET request with headers
response = requests.get(url, headers=headers)
# Print the response content
print("Response:", response.json())
import requests
# Define the API endpoint
url = "https://httpbin.org/cookies"
# Send a GET request with cookies
cookies = {'session_id': '12345'}
response = requests.get(url, cookies=cookies)
# Print the response
print("Response:", response.json()) # Prints the cookies that were sent
import requests
# Define the API endpoint
url = "https://httpbin.org/delay/5" # This endpoint delays the response by 5 seconds
# Make a GET request with a timeout
try:
response = requests.get(url, timeout=3) # Timeout after 3 seconds
print("Response:", response.json())
except requests.exceptions.Timeout:
print("Request timed out")
import requests
# Define the API endpoint
url = "https://httpbin.org/post"
# File to be uploaded
files = {'file': open('example.txt', 'rb')}
# Make a POST request to upload the file
response = requests.post(url, files=files)
# Print the response
if response.status_code == 200:
print("File uploaded successfully")
print("Response:", response.json())
else:
print("Failed to upload file:", response.status_code)
# Close the file
files['file'].close()
import requests
# Create a session object
session = requests.Session()
# Set some default headers for all requests made with this session
session.headers.update({'User-Agent': 'my-app/1.0'})
# Send a GET request with the session
response = session.get("https://httpbin.org/headers")
print("Response Headers:", response.json())
# You can also send requests with the session in the same way as requests
response = session.get("https://httpbin.org/cookies")
print("Response Cookies:", response.json())
# Close the session when done
session.close()