Sending HTTP Requests in Python with the requests Library
Learn how to use the Python requests library to make GET and POST HTTP requests, handle responses, work with JSON, and add headers and authentication in your code.
The Python requests library is the most popular way to make HTTP requests in Python. Whether you’re consuming a third-party API, scraping a webpage, or talking to your own backend, requests makes it clean and intuitive. Let’s cover everything you need to get started.
Installing and Making Your First Request
pip install requests
import requests
response = requests.get("https://api.github.com/users/kaikobud")
print(response.status_code) # 200
print(response.json()) # Python dict of the response body
response.status_code tells you if the request succeeded (200 = OK, 404 = Not Found, etc.). response.json() parses the JSON response body automatically.
GET Requests with Query Parameters
params = {
"q": "python flask",
"sort": "stars",
"per_page": 5
}
response = requests.get("https://api.github.com/search/repositories", params=params)
data = response.json()
for repo in data["items"]:
print(repo["full_name"], repo["stargazers_count"])
Pass query parameters as a dictionary — requests handles URL encoding for you.
POST Requests with JSON
payload = {
"title": "New Post",
"body": "This is the content.",
"userId": 1
}
response = requests.post(
"https://jsonplaceholder.typicode.com/posts",
json=payload # automatically sets Content-Type: application/json
)
print(response.status_code) # 201
print(response.json())
Adding Headers and Authentication
headers = {
"Authorization": "Bearer YOUR_API_TOKEN",
"Accept": "application/json"
}
response = requests.get("https://api.example.com/me", headers=headers)
Error Handling
try:
response = requests.get("https://api.example.com/data", timeout=5)
response.raise_for_status() # Raises an exception for 4xx/5xx responses
data = response.json()
except requests.exceptions.Timeout:
print("Request timed out")
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e}")
Always set a timeout — without it, your code can hang indefinitely if the server doesn’t respond.
Conclusion
The Python requests library is essential for any developer working with APIs. GET, POST, headers, auth, error handling — you now have all the basics. Practice by hitting a free public API like JSONPlaceholder or GitHub’s API and building something small with the data.
Read next: Building a REST API with Python and Flask
External resource: Requests Library Documentation
Related Articles
CSS Flexbox in Plain English: A Beginner's Guide
Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.
Docker for Backend Developers: A Practical Introduction
Learn how Docker works, why backend developers need it, and how to containerize your first Python or Go application in under 30 minutes.
Containerising a Backend Service: From Docker to Kubernetes
A practical walkthrough of containerising a Python backend service with Docker, deploying it to Kubernetes on ECS, and the production gaps that only show up once real traffic hits.