Consuming REST APIs with requests
What is a REST API?
A web service that returns data (usually JSON) when you send HTTP requests to a URL:
| Method | Meaning |
|---|---|
GET | read data |
POST | create |
PUT / PATCH | update |
DELETE | remove |
Status codes
200 OK · 201 created · 400 bad request · 401 not logged in · 403 forbidden · 404 not found · 429 too many requests · 500 server error.
requests basics
resp = requests.get(url, params={"q": "python"}, timeout=10)
resp.raise_for_status() # turns 4xx/5xx into an exception
data = resp.json()
- Always set a timeout, or a slow server can hang your program forever.
params=builds the query string safely;json=sends a JSON body with POST.- Use a
requests.Session()to reuse connections and headers for many calls.
💡 Read the API's documentation for its rate limits and authentication rules.
💻 requests needs a normal network connection, so run it on a computer.
Example
import requests
def get_github_user(username):
url = f"https://api.github.com/users/{username}"
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
except requests.exceptions.HTTPError:
print("User not found or API error:", resp.status_code)
return None
except requests.exceptions.RequestException as e:
print("Network problem:", e)
return None
return resp.json()
user = get_github_user("octocat")
if user:
print(user["login"], "has", user["public_repos"], "public repos")
# Sending data with POST
resp = requests.post(
"https://httpbin.org/post",
json={"name": "Ana", "course": "Python"},
timeout=10,
)
print(resp.status_code, resp.json()["json"])