requests is the most downloaded Python library in the world — over 300 million downloads per month. It makes HTTP requests simple and readable.
Installation
pip install requests
On CodeHS the library is already installed.
Basic GET Request
import requests
response = requests.get("https://api.chucknorris.io/jokes/random")
print(response.status_code) # 200
print(response.text) # raw response text
print(response.json()) # Python dict (if the response is JSON)
Parameters and Responses
Query Parameters (params)
Pass parameters as a dictionary — requests builds the correct URL for you:
# Bad — manual URL construction:
url = f"https://api.chucknorris.io/jokes/random?category={category}"
# Good — via params=:
response = requests.get(
"https://api.chucknorris.io/jokes/random",
params={"category": "dev"}
)
# Resulting URL: .../jokes/random?category=dev
If a parameter value contains special characters (&, /, spaces), params= URL-encodes them automatically. Manual construction will break in those cases.
timeout — Always Set It
response = requests.get(url, timeout=10)
# If the server doesn't respond within 10 seconds — raises Timeout
Without a timeout, your program can hang forever. In production code, timeout is mandatory.
response.json() vs response.text vs response.content
response = requests.get(url)
response.status_code # integer: 200, 404, 401...
response.text # string — raw response text
response.json() # Python dict/list (parses JSON)
response.content # bytes — binary data (images, files)
response.headers # dict of response headers
raise_for_status()
Automatically raises HTTPError if the status is >= 400:
response = requests.get(url)
response.raise_for_status() # no-op on 200, raises on 4xx/5xx
data = response.json()
More convenient than if response.status_code != 200: raise ....
Sending Data
POST Request with a Body
response = requests.post(
"https://api.github.com/user/repos",
headers={"Authorization": "Bearer TOKEN"},
json={"name": "my-repo", "private": False}, # request body
)
json= automatically:
- Serializes the dict to JSON
- Adds the Content-Type: application/json header
PATCH and Other Methods
requests.patch(url, headers=headers, json={"state": "closed"})
requests.delete(url, headers=headers)
requests.put(url, headers=headers, json={...})
# Or generically:
requests.request("PATCH", url, headers=headers, json={...})
Headers
headers = {
"Authorization": "Bearer my_token",
"Accept": "application/json",
}
response = requests.get(url, headers=headers)
Additional Features
Error Handling
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.ConnectionError:
print("No internet connection")
except requests.exceptions.Timeout:
print("Server did not respond")
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e.response.status_code}")
Downloading a File
response = requests.get(image_url, timeout=30)
response.raise_for_status()
with open("photo.jpg", "wb") as f:
f.write(response.content) # content is bytes, not text
Summary
| Task | How |
|---|---|
| GET request | requests.get(url, params={}, timeout=10) |
| POST request | requests.post(url, json={}, headers={}) |
| Response status | response.status_code |
| JSON data | response.json() |
| Auto-check status | response.raise_for_status() |
| Binary data | response.content |
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!