Explain it simply
Explain it simply
A REST API is like the counter of a restaurant. A customer (a mobile app, a website or another program) names a dish on the menu (a URL) and what it wants done (a method). The counter checks the order and hands back a plate (JSON) plus a slip that says how it went (a status code).
For example, GET /api/users/1 means "show me user 1" and POST /api/users means "create a new user". The customer never needs to know what happens in the kitchen, only the counter's rules. In this project you build that counter in Python.
Problem → Why → Solution
The problem: one route that does everything
When writing a first API, it is tempting to put everything in the route function: reading the body, writing SQL, sending the response. In the code below, a client that leaves out the email gets a KeyError and a 500 Internal Server Error. Because the SQL is built with an f-string, a user whose name contains a quote can even make the database run SQL of their choosing.
Even on success it answers 200 and the text "ok" instead of 201 Created and the new user, so the client never learns the new id. And testing this function needs a running server and a real database.
@app.post("/api/users")
def create():
data = request.json
db.execute(f"INSERT INTO users VALUES ('{data['name']}', '{data['email']}')")
return "ok" # 200, plain text, no id - and KeyError if email is missingWhy is this a problem?
One route is doing four jobs at once: HTTP, validation, business rules and storage. Changing any part risks the others, and every mistake reaches the client as an unhelpful 500. The client cannot tell what went wrong or how to fix its request.
Core concept: resources, methods, status codes, layers
REST design separates nouns from verbs. The URL names a resource (the noun): /api/users is the collection of users and /api/users/1 is one user. The HTTP method says what to do with it (the verb). So instead of a URL like /api/createUser, you write POST /api/users.
| Method | Meaning | If repeated |
|---|---|---|
| GET | Read; changes nothing | Same result (safe) |
| POST | Create in a collection | May create two records |
| PUT | Replace the whole resource | Same result (idempotent) |
| PATCH | Change only the sent fields | Depends on the design |
| DELETE | Remove the resource | Still gone (idempotent) |
Why does the "If repeated" column matter? On mobile networks a request can reach the server while its response gets lost. When the client retries, a second PUT or DELETE leaves the server in the same state, so the retry is safe. Retrying a POST, however, can create two users, so that case needs deliberate design.
Status codes report the outcome in a way machines can read: 2xx means success, 4xx means the client made a mistake, 5xx means the server failed. This project uses 200 OK, 201 Created (a successful POST), 204 No Content (a successful DELETE with no body), 400 Bad Request (an invalid body), 404 Not Found, 405 Method Not Allowed, and in the challenge 409 Conflict (a duplicate email). Error bodies share one shape, {"error": ...}, so a client can handle every error in one place.
Finally, the code is split into four layers. Routing sends a method and path to a function. Validation checks the body. Handlers apply the rules and return (status, body). The data layer stores things. Because the handlers know nothing about HTTP, you can test them by calling plain functions, without a server.
- Route method + path to a handler
- Validate the request body
- Apply the rule, change the data
- Return (status, JSON body)
Any step may return early with a 4xx; the data changes only after every check has passed.
General pattern
def create_item(body):
errors = validate(body)
if errors:
return 400, {"error": "validation failed", "fields": errors}
item = store.add(body)
return 201, {"data": item}
def get_item(item_id):
item = store.find(item_id)
if item is None:
return 404, {"error": f"item {item_id} not found"}
return 200, {"data": item}Every handler returns (status code, JSON-ready body). Check the error cases first and write the success path last.
A users API without a framework
This runnable example has no framework at all. handle() does the job Flask would do, matching a method and path to a function, so it runs anywhere without installing anything and shows plainly what a framework does for you. call() acts like a client: it sends a request and prints the status and the JSON.
Keep every response the same shape. If get_user() returned a dict on success but a tuple on failure, every caller would have to check the type, and deleting a missing user should never report success. Here every handler always returns (status, body).
import json
# ---- data layer: an in-memory "table" (a database in a real app) ----
users = {
1: {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"},
2: {"id": 2, "name": "Su Su", "email": "susu@example.com"},
}
next_id = 3
# ---- validation: never trust the request body ----
def validate_user(body):
errors = {}
name, email = body.get("name"), body.get("email")
if not isinstance(name, str) or not name.strip():
errors["name"] = "is required"
if not isinstance(email, str) or "@" not in email:
errors["email"] = "must be an email address"
return errors
# ---- handlers: each returns (status code, JSON-ready body) ----
def list_users():
return 200, {"data": list(users.values()), "count": len(users)}
def get_user(user_id):
if user_id not in users:
return 404, {"error": f"user {user_id} not found"}
return 200, {"data": users[user_id]}
def create_user(body):
global next_id
errors = validate_user(body)
if errors:
return 400, {"error": "validation failed", "fields": errors}
user = {"id": next_id, "name": body["name"].strip(), "email": body["email"]}
users[next_id] = user
next_id += 1
return 201, {"data": user}
def delete_user(user_id):
if users.pop(user_id, None) is None:
return 404, {"error": f"user {user_id} not found"}
return 204, None
# ---- routing: method + path -> handler (Flask does this part for you) ----
def handle(method, path, body=None):
parts = path.strip("/").split("/") # "/api/users/1" -> [..., "1"]
if parts[:2] != ["api", "users"] or len(parts) > 3:
return 404, {"error": "no such endpoint"}
if len(parts) == 2:
routes = {"GET": list_users, "POST": lambda: create_user(body or {})}
elif parts[2].isdigit():
uid = int(parts[2])
routes = {"GET": lambda: get_user(uid), "DELETE": lambda: delete_user(uid)}
else:
return 404, {"error": "user id must be a number"}
if method not in routes:
return 405, {"error": f"{method} is not allowed on {path}"}
return routes[method]()
def call(method, path, body=None):
status, payload = handle(method, path, body)
line = f"{method} {path} -> {status}"
if payload is not None:
line += " " + json.dumps(payload)
print(line)
call("GET", "/api/users/1")
call("POST", "/api/users", {"name": "Min Min", "email": "minmin@example.com"})
call("POST", "/api/users", {"name": " ", "email": "no-at-sign"})
call("DELETE", "/api/users/2")
call("DELETE", "/api/users/2")
call("PUT", "/api/users")
status, payload = handle("GET", "/api/users")
print("GET /api/users ->", status, "count =", payload["count"])Code breakdown
- Validation returns errors, not exceptions
def validate_user(body):Problems are collected per field in a dictionary, so the client learns about every mistake in one round trip. The isinstance() checks also catch a name sent as a number such as 123.
- 201 with the new resource
return 201, {"data": user}A successful POST answers 201 Created with the stored user, id included, so the client can use /api/users/3 in later requests.
- Honest DELETE
if users.pop(user_id, None) is None:pop() returns the default None when the key is missing, so the first DELETE gets 204 and the second gets 404. The server state is the same after both calls, so DELETE is still idempotent.
- A route table per path
routes = {"GET": list_users, "POST": lambda: create_user(body or {})}Each path lists its allowed methods in a dictionary. The lambda delays the call, so a handler runs only when its method matches.
- 405, not 404
if method not in routes:The path exists but this method is not allowed, which is 405. Answering 404 would make the client think the URL itself was wrong.
- Real JSON on the wire
line += " " + json.dumps(payload)json.dumps() produces real JSON with double quotes. The original printed Python dicts directly, and a repr like {'id': 1} is not valid JSON.
GET /api/users/1 -> 200 {"data": {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"}}
POST /api/users -> 201 {"data": {"id": 3, "name": "Min Min", "email": "minmin@example.com"}}
POST /api/users -> 400 {"error": "validation failed", "fields": {"name": "is required", "email": "must be an email address"}}
DELETE /api/users/2 -> 204
DELETE /api/users/2 -> 404 {"error": "user 2 not found"}
PUT /api/users -> 405 {"error": "PUT is not allowed on /api/users"}
GET /api/users -> 200 count = 2The same API on Flask
Because the handlers only return (status, body), moving to Flask changes very little: delete handle() and replace it with route decorators. Flask's <int:user_id> converter turns a non-numeric id into a 404, and a method with no route gets a 405 automatically. When a route function returns a dict, Flask converts it into a JSON response.
The snippet below assumes the handlers have moved into a users_service.py module. It needs a Flask project to run, so it is not executed in this lesson.
# app.py - the same endpoints on Flask (pip install flask)
# Run locally with: flask --app app run --debug (never --debug in production)
from flask import Flask, request
from users_service import create_user, delete_user, get_user, list_users
app = Flask(__name__)
@app.get("/api/users")
def users_index():
status, body = list_users()
return body, status # Flask turns a dict into a JSON response
@app.get("/api/users/<int:user_id>") # a non-number id is a 404 automatically
def users_show(user_id):
status, body = get_user(user_id)
return body, status
@app.post("/api/users")
def users_create():
payload = request.get_json(silent=True) or {} # bad or missing JSON -> {}
status, body = create_user(payload)
return body, status
@app.delete("/api/users/<int:user_id>")
def users_delete(user_id):
status, body = delete_user(user_id)
return ("", 204) if status == 204 else (body, status)
# A test without starting a server:
# client = app.test_client()
# resp = client.post("/api/users", json={"name": "Min", "email": "min@example.com"})
# assert resp.status_code == 201 and resp.get_json()["data"]["id"] == 3In real projects
In real projects
A production API replaces the in-memory dictionary with a database such as SQLite or PostgreSQL, accessed through parameterized queries or an ORM like SQLAlchemy. Each request is authenticated with a token, and the API checks that this user may change this record (authorization). Collections with thousands of users are returned with pagination such as ?page=2&limit=50, and a version in the URL like /api/v1/ keeps older clients working.
Teams describe their endpoints in an OpenAPI document, and frontend developers work against that contract. Flask's built-in server is for development only, so in production the app runs behind a WSGI server such as Gunicorn, usually with a /health endpoint for the load balancer to check.
Common mistakes
Common mistakes
Answering 200 to everything
Writing {"status": "error"} in the body but answering 200 makes client libraries, monitoring tools and caches treat the failure as a success. Use a 4xx or 5xx code for every error.
Trusting the request body
Reading body["email"] directly turns a request without that field into a KeyError and a 500. A client can send anything, so check presence and type first and answer 400.
Building SQL with f-strings
Pasting user input into an SQL string opens the door to SQL injection. Always use parameterized queries such as cursor.execute("INSERT INTO users VALUES (?, ?)", (name, email)).
Running debug mode in production
Flask's debug mode enables an interactive debugger that can run Python code from the browser. Leaving it on for a public server is close to handing the machine to strangers.
Mini challenge
Add PATCH /api/users/<id>
Write an update_user(user_id, body) handler that changes only the fields it receives and, like the example's handlers, returns (status, body).
- Return 404 when the user does not exist
- Return 400 for an empty body or any field other than name and email
- Return 400 for an empty name or an email without @
- Return 409 Conflict when another user already has that email
- On success return 200 and the updated user
users = {
1: {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"},
2: {"id": 2, "name": "Su Su", "email": "susu@example.com"},
}
EDITABLE = {"name", "email"}
def update_user(user_id, body):
"""PATCH /api/users/<id>"""
# TODO: 404 if the user is missing
# TODO: 400 if body is empty or has keys outside EDITABLE
# TODO: 400 for an empty name or an email without "@"
# TODO: 409 if another user already owns the email
# TODO: apply the changes and return 200 with the user
...
# TODO: call update_user for each case and print the (status, body) tuplesExpected: Renaming gets 200, user 9 gets 404, a role field gets 400, user 1 taking Su Su's email gets 409, and Su Su changing her own email gets 200.
Show hint
set(body) - EDITABLE gives the keys that are not allowed. For duplicates, use any(u["email"] == new_email and u["id"] != user_id for u in users.values()). Call users[user_id].update(body) only after every check has passed.
Show solution
users = {
1: {"id": 1, "name": "Aung Kyaw", "email": "aung@example.com"},
2: {"id": 2, "name": "Su Su", "email": "susu@example.com"},
}
EDITABLE = {"name", "email"}
def update_user(user_id, body):
"""PATCH /api/users/<id>: change only the fields that were sent."""
if user_id not in users:
return 404, {"error": f"user {user_id} not found"}
unknown = set(body) - EDITABLE
if not body or unknown:
return 400, {"error": f"send name and/or email only, got {sorted(unknown)}"}
if "name" in body and not str(body["name"]).strip():
return 400, {"error": "name cannot be empty"}
if "email" in body:
if "@" not in str(body["email"]):
return 400, {"error": "email must contain @"}
taken = any(u["email"] == body["email"] and u["id"] != user_id
for u in users.values())
if taken:
return 409, {"error": "email already used by another user"}
users[user_id].update(body)
return 200, {"data": users[user_id]}
print(update_user(1, {"name": "Aung Kyaw Moe"}))
print(update_user(9, {"name": "Nobody"}))
print(update_user(1, {"role": "admin"}))
print(update_user(1, {"email": "susu@example.com"}))
print(update_user(2, {"email": "su.su@example.com"}))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- The URL names the resource (noun); the HTTP method is the action (verb)
- Match 201, 204, 400, 404, 405 and 409 to their situations and keep one error body shape
- Never trust the request body; validate every field
- Handlers that return (status, body) are testable without a server and plug straight into Flask
Requests — User Guide — Requests