HTTP Requests with the requests Library (GET, POST, JSON, Sessions) - Python #32
Video: HTTP Requests with the requests Library (GET, POST, JSON, Sessions) - Python #32 by Taught by Celeste AI - AI Coding Coach
Watch full page →HTTP Requests with the requests Library in Python
Python's requests library simplifies interacting with REST APIs by providing intuitive methods to send HTTP requests. You can easily fetch data using GET requests, send data with POST, and manage sessions for efficient communication with APIs.
Code
import requests
# Define the base URL for the API
BASE_URL = "https://jsonplaceholder.typicode.com"
# Example: GET request to fetch posts with query parameters
params = {"userId": 1} # filter posts by userId
response = requests.get(f"{BASE_URL}/posts", params=params)
response.raise_for_status() # raise exception for HTTP errors
posts = response.json() # parse JSON response into Python list/dict
print("User 1 posts:", posts)
# Example: POST request to create a new post
new_post = {
"title": "foo",
"body": "bar",
"userId": 1
}
response = requests.post(f"{BASE_URL}/posts", json=new_post)
response.raise_for_status()
created_post = response.json()
print("Created post:", created_post)
# Using a session to persist headers and improve performance
session = requests.Session()
session.headers.update({"Authorization": "Bearer YOUR_API_TOKEN"})
try:
# GET request with session and timeout
resp = session.get(f"{BASE_URL}/posts/1", timeout=5)
resp.raise_for_status()
post = resp.json()
print("Post 1 details:", post)
except requests.exceptions.RequestException as e:
print("Request failed:", e)
# Clean up session
session.close()
Key Points
- Use
requests.get()with query parameters to retrieve filtered API data. - Send JSON data easily with
requests.post()by passing thejsonargument. - Call
raise_for_status()to handle HTTP errors gracefully. - Sessions allow reusing connections and sharing headers like authentication tokens.
- Always set timeouts to avoid hanging on slow or unresponsive servers.