Explain it simply
Explain it simply
Picture a library catalogue. The /books shelf holds every book and /books/42 is book number 42. Whether you want to look at a book, add a new one, edit one or remove one, the place (the URL) stays the same; only the action (the HTTP method) changes.
A REST API follows the same rule: URLs are nouns (resources), GET, POST, PATCH and DELETE are verbs, and the status code tells you the outcome. In this lesson you write a tidy Python client for such an API.
Problem → Why → Solution
The problem: every call site builds its own request
Early in a project, API functions get written ad hoc. In the code below, delete_todo() forgets the Authorization header and calls .json() on a 204 response that has no body, so it crashes. safe_call() turns every exception into an {"error": ...} dict, so the caller can no longer tell "no such todo" from "server down" from a typo in the code.
def get_todo(todo_id):
r = requests.get(f"{BASE}/todos/{todo_id}", headers={"Authorization": KEY})
return r.json()
def delete_todo(todo_id):
r = requests.delete(BASE + "/todos/" + str(todo_id)) # auth header forgotten
return r.json() # 204 has no body: crash
def safe_call(fn, *args):
try:
return fn(*args)
except Exception as e: # 404, timeouts and typos all look the same
return {"error": str(e)}Why does this keep happening?
The contract with the API, meaning the base URL, auth, timeout, how to check the status and how to treat a response with no body, is not written down in one place; every call site re-creates it by hand. Forget it once and you have a bug, and changing it means hunting down every copy. A client class writes the contract once and everyone reuses it.
Core concept: resources, methods, statuses and one client
In a REST-style API each kind of data is a resource: a plural noun such as /todos names the collection and /todos/2 names one item by id. The HTTP method states the operation, and the server answers with a status code and a JSON representation. Every request carries everything the server needs, including the auth token, because the server keeps no session state about the client (it is stateless). A version in the URL, such as /v1, lets the API evolve without breaking older clients. Filtering and sorting usually travel as query parameters, as in GET /todos?done=false&sort=-created, while the path keeps naming only the resource.
| Operation | Method and path | Success status |
|---|---|---|
| List | GET /todos?page=1&limit=20 | 200 OK |
| Read one | GET /todos/2 | 200 OK (404 if missing) |
| Create | POST /todos | 201 Created |
| Update some fields | PATCH /todos/2 | 200 OK |
| Delete | DELETE /todos/2 | 204 No Content (no body) |
Error statuses are precise too: 400 or 422 means the data you sent is invalid, 401 means you are not authenticated (a bad token), 403 means you are authenticated but not allowed, 404 means the resource does not exist, and 409 means a conflict with the current state, such as a duplicate name.
A good client has three parts. First, it accepts the Session in its constructor (dependency injection), so production passes requests.Session() and tests pass a fake. Second, a single _call() method joins the base URL, adds headers, applies the timeout, calls raise_for_status() and turns an empty body into None. Third, each public method matches one API operation and has a clear name. POST is not idempotent, so if creations must be retried, use a mechanism such as an Idempotency-Key header when the API supports one.
- A public method picks the operation
- _call() adds URL, headers, timeout
- raise_for_status() checks the status
- JSON or None comes back
When the API contract changes, you edit _call() and nothing else.
General pattern
class ResourceClient:
def __init__(self, session, base_url, token, timeout=5):
... # store them; build the auth header once
def _call(self, method, path, body=None):
resp = self.session.request(method, self.base_url + path, headers=...,
timeout=self.timeout, json=body)
resp.raise_for_status()
return resp.json() if resp.content else None
def operation_name(self, item_id):
return self._call("VERB", f"/resources/{item_id}")Every request detail lives in _call(); the public methods only choose a verb and a path. Checking resp.content keeps .json() away from body-less responses such as 204.
Example: a todo client against a fake server
FakeTodoServer accepts the same arguments as requests.Session's .request() and returns real requests.Response objects, so raise_for_status() behaves exactly as it would in production. TodoClient is production code: put requests.Session() where FakeTodoServer() is and it calls a real API. We create, update, delete and list, then try to fetch a deleted todo.
import json
import os
from http import HTTPStatus
import requests
def make_response(status, data=None):
resp = requests.Response()
resp.status_code, resp.reason = status, HTTPStatus(status).phrase
resp._content = b"" if data is None else json.dumps(data).encode()
return resp
class FakeTodoServer:
"""Offline stand-in with the same .request() shape as requests.Session."""
def __init__(self):
self.todos = {1: {"id": 1, "title": "Learn REST", "done": False}}
def request(self, method, url, headers=None, timeout=None, json=None):
if headers.get("Authorization") != "Bearer demo-token":
return make_response(401, {"error": "missing or bad token"})
path = url.split("/v1", 1)[1] # "/todos" or "/todos/<id>"
if path == "/todos":
if method == "POST":
new_id = max(self.todos, default=0) + 1
self.todos[new_id] = {"id": new_id, "done": False, **json}
return make_response(201, self.todos[new_id])
return make_response(200, list(self.todos.values()))
todo = self.todos.get(int(path.rsplit("/", 1)[1]))
if todo is None:
return make_response(404, {"error": "todo not found"})
if method == "PATCH":
todo.update(json)
elif method == "DELETE":
del self.todos[todo["id"]]
return make_response(204)
return make_response(200, todo)
class TodoClient:
"""One method per REST operation on the /todos resource."""
def __init__(self, session, base_url, token, timeout=5):
self.session, self.base_url, self.timeout = session, base_url, timeout
self.headers = {"Authorization": f"Bearer {token}"}
def _call(self, method, path, body=None):
resp = self.session.request(method, self.base_url + path, headers=self.headers,
timeout=self.timeout, json=body)
resp.raise_for_status()
return resp.json() if resp.content else None
def list(self):
return self._call("GET", "/todos")
def get(self, todo_id):
return self._call("GET", f"/todos/{todo_id}")
def create(self, title):
return self._call("POST", "/todos", {"title": title})
def update(self, todo_id, **fields):
return self._call("PATCH", f"/todos/{todo_id}", fields)
def delete(self, todo_id):
return self._call("DELETE", f"/todos/{todo_id}")
token = os.environ.get("TODO_API_TOKEN", "demo-token") # never hard-code real keys
api = TodoClient(FakeTodoServer(), "https://api.example.com/v1", token)
print("created:", api.create("Write tests"))
print("updated:", api.update(2, done=True))
print("deleted:", api.delete(1))
print("list:", api.list())
try:
api.get(1)
except requests.exceptions.HTTPError as e:
print("error:", e.response.status_code, e.response.json()["error"])Code breakdown
- Injected session
api = TodoClient(FakeTodoServer(), "https://api.example.com/v1", token)The client receives its session instead of creating one, so a fake can be injected. The token is read from an environment variable, falling back to a demo value only when it is missing.
- One funnel
resp = self.session.request(method, self.base_url + path, headers=self.headers,Every request passes through this line, so the auth header and the timeout can never be forgotten.
- Empty body
return resp.json() if resp.content else NoneDELETE returns 204 No Content, so resp.content is b"". That is why the output shows "deleted: None" instead of a JSONDecodeError.
- PATCH
return self._call("PATCH", f"/todos/{todo_id}", fields)**fields gathers update(2, done=True) into {"done": True}, and PATCH changes only the fields it receives, so the title survives.
- 404 surfaces
except requests.exceptions.HTTPError as e:Todo 1 has been deleted, so the server answers 404 and raise_for_status() raises HTTPError. e.response provides the status and the server's error message.
created: {'id': 2, 'done': False, 'title': 'Write tests'}
updated: {'id': 2, 'done': True, 'title': 'Write tests'}
deleted: None
list: [{'id': 2, 'done': True, 'title': 'Write tests'}]
error: 404 todo not found
Pagination: reading every page
List endpoints rarely return everything at once; they split results into pages such as ?page=1&limit=20, and reading only the first page silently loses data. The generator below fetches one page at a time and stops at the first page shorter than the limit. When the total is an exact multiple of the limit, it costs one extra request for an empty page. Some APIs return a next cursor or a Link header instead of page numbers, but the loop has the same shape.
ALL_TODOS = [{"id": i} for i in range(1, 8)]
def fetch_page(page, limit): # stands in for GET /todos?page=<page>&limit=<limit>
start = (page - 1) * limit
return ALL_TODOS[start:start + limit]
def iter_todos(fetch, limit=3):
page = 1
while True:
batch = fetch(page, limit)
yield from batch
if len(batch) < limit: # a short page means it was the last one
break
page += 1
print([todo["id"] for todo in iter_todos(fetch_page)])In real projects
Where this shows up in real projects
You meet this client-class shape in every project that integrates payments, SMS, shipping or a CRM. Official Python SDKs published by providers are often built the same way inside: one Session, one request funnel and a set of error classes. When you write your own client, translate the API's HTTP errors into domain exceptions such as PaymentDeclined or CityNotFound, so the rest of the code deals with business logic and never with HTTP details.
When teams test a client, they inject a fake session as in the example and check that the client reacts correctly to each status: 201, 204, 404, 409 and 500. From the API design side, writing the endpoints, statuses, error format and pagination of a todo CRUD API into a table first, and getting both the client and server teams to agree before coding, saves many arguments later.
Common mistakes
Common mistakes
1. Swallowing every exception into an error dict
except Exception: return {"error": str(e)} makes a 404, a timeout and an AttributeError in your own code look identical, and a caller that treats the dict as data fails mysteriously somewhere else. Convert only the statuses you can handle into domain exceptions and let the rest propagate.
2. Calling .json() on a 204 response
Most DELETE endpoints return 204 No Content with no body at all, so .json() raises JSONDecodeError. Check resp.content or status_code == 204 first.
3. Using only 200 and 500
If a server answers 200 for every success and 500 for every failure, clients cannot tell whether to fix their data or wait and retry, and monitoring mixes client mistakes with real outages. Use precise codes such as 201, 204, 400, 404 and 409.
4. Reading only the first page
With a little test data everything fits on one page and the code seems fine, but production returns only the first 20 items. Check the documentation of every list endpoint for pagination and read it with a loop.
Mini challenge
Mini challenge: a weather client
Write a WeatherClient for a GET /current?city=...&key=... endpoint. To avoid the network, also write a fake server with a .get() method and inject it into the client.
- The fake server returns 401 for a wrong key, 404 for a city missing from CITIES, and 200 with JSON otherwise, using requests.Response
- WeatherClient takes session, base_url, api_key and timeout in its constructor
- current(city) raises CityNotFound on 404 and lets raise_for_status() raise for other error statuses
- On success it returns a dict with only the keys city, temp_c and condition
import json
from http import HTTPStatus
import requests
CITIES = {"yangon": {"temp_c": 32, "condition": "Sunny", "humidity": 65}}
class FakeWeatherServer:
def get(self, url, params=None, timeout=None):
# TODO: 401 for a wrong key, 404 for an unknown city, else 200 + data
# TODO: return a requests.Response with status_code, reason and _content
...
class CityNotFound(Exception):
pass
class WeatherClient:
def __init__(self, session, base_url, api_key, timeout=5):
... # TODO: store everything
def current(self, city):
# TODO: GET {base_url}/current with params city and key, plus a timeout
# TODO: 404 -> CityNotFound(city); other errors -> raise_for_status()
# TODO: return {"city": ..., "temp_c": ..., "condition": ...}
...
# TODO: print Yangon's weather, catch CityNotFound for "Mandalay",
# and show the 401 that a client with a wrong key receivesExpected: Three lines of output: {'city': 'Yangon', 'temp_c': 32, 'condition': 'Sunny'} no data for Mandalay auth problem: 401 Unauthorized
Show hint
HTTPStatus(status).phrase gives reasons such as "Not Found" for 404. Normalise the city with .lower() before looking it up in CITIES. Check for CityNotFound before calling raise_for_status(), or the HTTPError fires first.
Show solution
import json
from http import HTTPStatus
import requests
CITIES = {"yangon": {"temp_c": 32, "condition": "Sunny", "humidity": 65}}
class FakeWeatherServer:
def get(self, url, params=None, timeout=None):
if params.get("key") != "demo-key":
status, data = 401, {"error": "invalid key"}
elif params["city"].lower() in CITIES:
status, data = 200, CITIES[params["city"].lower()]
else:
status, data = 404, {"error": "unknown city"}
resp = requests.Response()
resp.status_code, resp.reason = status, HTTPStatus(status).phrase
resp._content = json.dumps(data).encode()
return resp
class CityNotFound(Exception):
pass
class WeatherClient:
def __init__(self, session, base_url, api_key, timeout=5):
self.session, self.base_url = session, base_url
self.api_key, self.timeout = api_key, timeout
def current(self, city):
resp = self.session.get(f"{self.base_url}/current",
params={"city": city, "key": self.api_key},
timeout=self.timeout)
if resp.status_code == 404:
raise CityNotFound(city)
resp.raise_for_status()
data = resp.json()
return {"city": city, "temp_c": data["temp_c"], "condition": data["condition"]}
server = FakeWeatherServer()
client = WeatherClient(server, "https://weather.example.com/v1", "demo-key")
print(client.current("Yangon"))
try:
client.current("Mandalay")
except CityNotFound as e:
print("no data for", e)
try:
WeatherClient(server, "https://weather.example.com/v1", "wrong").current("Yangon")
except requests.exceptions.HTTPError as e:
print("auth problem:", e.response.status_code, e.response.reason)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- In REST, the URL is the resource (a noun), the HTTP method is the action (a verb) and the status code is the outcome.
- Distinguish and use 201 Created, 204 No Content, 400, 401, 403, 404 and 409.
- Keep the base URL, auth, timeout and status check in one _call() method of a client class.
- Inject the session to test with a fake, and read list endpoints with a pagination loop.
Requests — User Guide — Requests