Path Operations and HTTP Methods
Build a small to-do API with all five common HTTP methods - GET, POST, PUT, PATCH and DELETE - and the right status codes. Then test the mistakes: a wrong method, a trailing slash, routes in the wrong order, and a route defined twice.
What you will be able to do
- Explain what a path operation is: a method, a path and a function
- Use GET, POST, PUT, PATCH and DELETE for what each one means
- Set the right status code: 200, 201, 204, 404
- Test an API quickly with TestClient
- Explain 404, 405, 307 and 422 when you see them
- Order routes correctly, and avoid duplicates
The idea, in plain English
An API does more than read: it creates, changes and deletes. HTTP has a method for each job - GET reads, POST creates, PUT replaces, PATCH changes part, DELETE removes - and FastAPI has one decorator for each: @app.get, @app.post, @app.put, @app.patch, @app.delete.
A method plus a path is a path operation. GET /todos and POST /todos share a path but are two different operations, each with its own function.
We build a small to-do API with its data in a Python dict (a database comes in Module 5), test every operation, set the right status codes, and try the mistakes that confuse beginners. FastAPI 0.143.0, Starlette 1.7.0.
Worked example: An in-memory to-do API: list, read, create (201), replace, update (exercise) and delete (204) - tested with TestClient and curl.
1 - Create: POST /todos -> 201
The client sends {"title": "Call the bank"}. create_todo gives it id 2 and answers 201 Created with the new to-do.
Real runs of the to-do API. The method decides which function runs, and each answers with its own status code.
Words you will see in this lesson
A few words about routes and methods.
PathThe part of the URL after the address: /todos, /todos/2.HTTP methodWhat the client wants to do: GET, POST, PUT, PATCH, DELETE.Path operationA method plus a path, handled by one function: POST /todos.CRUDCreate, Read, Update, Delete - the four basic jobs of most APIs.Status codeThe result number: 200 OK, 201 Created, 204 No Content, 404, 405, 422.IdempotentDoing it twice has the same effect as doing it once (PUT, DELETE).TestClientSends real requests to your app inside Python - no server needed.An everyday example: a library desk
At a library desk, the same book number can mean different things:
- "Show me book 42" - reading (GET).
- "Please add this new book" - creating (POST).
- "Replace the record for book 42 with this one" - PUT.
- "Just change the shelf number of book 42" - PATCH.
- "Remove book 42" - DELETE.
- The book number (the path) stays the same; the request type (the method) decides what happens.
GETRead. Never changes data. Safe to repeat.POSTCreate something new. Repeating it creates another one.PUTReplace the whole thing with what you send. Repeating it gives the same result.PATCHChange only the fields you send.DELETERemove it. Repeating it does not remove more (the second time: 404).Example 1 - the to-do API
The whole API. Read it in three parts:
- TODOS - a dict holding the data. Lost when the server restarts; fine for learning.
- TodoIn - the shape of the JSON a client sends: title (required) and done (optional, false by default). Lesson 1.6 explains models.
- Status codes: POST uses 201 (Created); DELETE uses 204 (No Content) and returns nothing; an unknown to-do raises HTTPException(404). Everything else is 200.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class TodoIn(BaseModel): # what the client sends (Lesson 1.6 explains this)
title: str
done: bool = False
TODOS = {1: {"id": 1, "title": "Buy milk", "done": False}} # our "database": a dict in memory
next_id = 2
@app.get("/todos") # READ all
def list_todos():
return list(TODOS.values())
@app.get("/todos/{todo_id}") # READ one
def get_todo(todo_id: int):
if todo_id not in TODOS:
raise HTTPException(status_code=404, detail="Todo not found")
return TODOS[todo_id]
@app.post("/todos", status_code=201) # CREATE
def create_todo(todo: TodoIn):
global next_id
TODOS[next_id] = {"id": next_id, **todo.model_dump()}
next_id += 1
return TODOS[next_id - 1]
@app.put("/todos/{todo_id}") # REPLACE
def replace_todo(todo_id: int, todo: TodoIn):
if todo_id not in TODOS:
raise HTTPException(status_code=404, detail="Todo not found")
TODOS[todo_id] = {"id": todo_id, **todo.model_dump()}
return TODOS[todo_id]
@app.delete("/todos/{todo_id}", status_code=204) # DELETE
def delete_todo(todo_id: int):
if TODOS.pop(todo_id, None) is None:
raise HTTPException(status_code=404, detail="Todo not found")Example 2 - test it with TestClient
- TestClient sends real HTTP requests to your app from inside Python - no server, no second terminal. Module 9 uses it for tests.
- client.request(method, url, json=...) sends a request; the response has .status_code and .text.
- Read the output top to bottom: list (200), create (201, id 2), read (200), replace (200, done: true), delete to-do 1 (204, empty), read it again (404), final list - only to-do 2 is left.
from fastapi.testclient import TestClient
from todos import app
client = TestClient(app) # sends real HTTP requests to the app, without a server
def show(method, url, **kw):
r = client.request(method, url, follow_redirects=False, **kw)
body = r.text if r.text else "(empty)"
extra = f" Allow: {r.headers['allow']}" if "allow" in r.headers else ""
extra += f" Location: {r.headers['location']}" if "location" in r.headers else ""
print(f"{method:6} {url:14} -> {r.status_code} {body[:90]}{extra}")
show("GET", "/todos")
show("POST", "/todos", json={"title": "Call the bank"})
show("GET", "/todos/2")
show("PUT", "/todos/2", json={"title": "Call the bank", "done": True})
show("DELETE", "/todos/1")
show("GET", "/todos/1")
show("GET", "/todos")
print("--- mistakes")
show("POST", "/todos/2", json={"title": "x"})
show("PATCH", "/todos/2", json={"done": False})
show("GET", "/todos/")
show("GET", "/Todos")
show("HEAD", "/todos")
show("POST", "/todos", json={"done": True})GET /todos -> 200 [{"id":1,"title":"Buy milk","done":false}]
POST /todos -> 201 {"id":2,"title":"Call the bank","done":false}
GET /todos/2 -> 200 {"id":2,"title":"Call the bank","done":false}
PUT /todos/2 -> 200 {"id":2,"title":"Call the bank","done":true}
DELETE /todos/1 -> 204 (empty)
GET /todos/1 -> 404 {"detail":"Todo not found"}
GET /todos -> 200 [{"id":2,"title":"Call the bank","done":true}]Watch out: With Starlette 1.7.0, importing TestClient printed a warning: "Using httpx with starlette.testclient is deprecated; install httpx2 instead." It still works. If you see it, the tools are moving to a new HTTP library - check the Starlette notes for your version.
The same API with curl
From the terminal, use curl with a running server (fastapi dev todos.py):
- -X sets the method, -H adds a header, -d sends a body.
- For JSON you must send Content-Type: application/json.
- The last request forgot to send JSON ("title=Pay rent"), so FastAPI answered 422 "JSON decode error".
$ curl -X POST localhost:8120/todos -H "Content-Type: application/json" -d '{"title": "Pay rent"}'
{"id":2,"title":"Pay rent","done":false} [201]
$ curl localhost:8120/todos
[{"id":1,"title":"Buy milk","done":false},{"id":2,"title":"Pay rent","done":false}] [200]
$ curl -X DELETE localhost:8120/todos/2
[204]
$ curl -X POST localhost:8120/todos -H "Content-Type: application/json" -d 'title=Pay rent'
{"detail":[{"type":"json_invalid","loc":["body",0],"msg":"JSON decode error","input":{},"ctx":{"error":"Expecting value"}}]} [422]Status codes: which one when
- The status code is the first thing a client checks - choose it on purpose.
- FastAPI uses 200 unless you set status_code in the decorator. Raise HTTPException for errors.
- /docs lists the success codes we set (201, 204) and adds 422 wherever there is input to check.
- It does NOT list the 404 we raise inside the functions - FastAPI cannot see inside your code. Module 3 shows how to document it.
GET /todos List Todos -> ['200']
POST /todos Create Todo -> ['201', '422']
GET /todos/{todo_id} Get Todo -> ['200', '422']
PUT /todos/{todo_id} Replace Todo -> ['200', '422']
DELETE /todos/{todo_id} Delete Todo -> ['204', '422']200 OKSuccess, with data. The default.201 CreatedSomething new was created (POST).204 No ContentSuccess, nothing to send back (DELETE). The body must be empty.307 Temporary RedirectGo to another URL - FastAPI uses it for a trailing slash.404 Not FoundNo such path - or no such item (we raise it).405 Method Not AllowedThe path exists, but not with this method.422 Unprocessable EntityThe input failed the checks: wrong type, missing field, bad JSON.Mistakes, tested: 405, 307, 404 and 422
- Wrong method: POST and PATCH on /todos/2 gave 405 Method Not Allowed. The Allow header said only "GET", although PUT and DELETE work too - each decorator is its own route. Do not rely on Allow; look at /docs.
- Trailing slash: GET /todos/ gave 307, a redirect to /todos. Some clients do not follow redirects, and each costs an extra round trip. Call the exact path.
- Wrong case: GET /Todos gave 404. Paths are case-sensitive.
- HEAD: HEAD /todos gave 405 - a GET route does not answer HEAD automatically in this version.
- Missing field: POST /todos with {"done": true} gave 422 "Field required" at body -> title.
POST /todos/2 -> 405 {"detail":"Method Not Allowed"} Allow: GET
PATCH /todos/2 -> 405 {"detail":"Method Not Allowed"} Allow: GET
GET /todos/ -> 307 (empty) Location: http://testserver/todos
GET /Todos -> 404 {"detail":"Not Found"}
HEAD /todos -> 405 (empty) Allow: GET
POST /todos -> 422 {"detail":[{"type":"missing","loc":["body","title"],"msg":"Field required","input":{"done"Route order: the first match wins
FastAPI checks routes in the order you wrote them, and the first match wins:
- We added GET /todos/latest AFTER GET /todos/{todo_id}.
- /todos/latest matched /todos/{todo_id} first, "latest" is not an int, and the answer was 422. latest() never ran.
- Fix: put fixed paths BEFORE paths with parameters. Then it answered 200.
- A route defined twice (same method and path) is not an error: the first answered every request, the second was dead code. Keep each operation in one place.
wrong = FastAPI()
@wrong.get("/todos/{todo_id}")
def get_todo(todo_id: int):
return {"todo": todo_id}
@wrong.get("/todos/latest") # declared AFTER the {todo_id} route
def latest():
return {"todo": "the latest one"}
right = FastAPI()
@right.get("/todos/latest") # fixed paths FIRST
def latest2():
return {"todo": "the latest one"}
@right.get("/todos/{todo_id}")
def get_todo2(todo_id: int):
return {"todo": todo_id}
dup = FastAPI()
@dup.get("/hello")
def first():
return {"from": "first"}
@dup.get("/hello") # the same method and path again
def second():
return {"from": "second"}wrong order GET /todos/latest -> 422 {"detail":[{"type":"int_parsing","loc":["path","todo_id"],"msg":"Input should be a valid integer, unable to pa
right order GET /todos/latest -> 200 {"todo":"the latest one"}
duplicate GET /hello -> 200 {"from":"first"}
duplicate: routes registered for /hello: ['/hello', '/hello']PUT or PATCH?
- PUT replaces the whole to-do: the client sends every field. A field left out becomes its default (done -> false), not "unchanged".
- PATCH changes only the fields the client sends - often what a user wants ("just tick it done").
- The key is model_dump(exclude_unset=True): only the fields the client really sent.
- Without it, sending only {"done": true} set the title to None - wiped out. (Your exercise below.)
Path operations at a glance
ReadDefault status 200.
@app.get("/todos")CreateSay it was created.
@app.post("/todos", status_code=201)ReplaceThe whole object.
@app.put("/todos/{todo_id}")Update partOnly sent fields.
@app.patch("/todos/{todo_id}")DeleteReturn nothing.
@app.delete("/todos/{todo_id}", status_code=204)Not foundAn error with a status.
raise HTTPException(status_code=404, detail="Todo not found")
Test quicklyNo server needed.
TestClient(app).post("/todos", json={...})Only sent fieldsFor PATCH.
changes.model_dump(exclude_unset=True)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Run fastapi dev todos.py, open /docs, and create, read and delete a to-do with "Try it out". Compare the status codes with the table above.”
“Add GET /todos/count after GET /todos/{todo_id}. What happens? Move it and try again.”
“Send the same POST twice. How many to-dos do you get? Now send the same PUT twice. What changes?”
“Run curl -i localhost:8000/todos/ and then curl -iL. What does -L change?”
What usually goes wrong
GET must only read. Browsers, caches and crawlers may repeat GET requests by themselves.
✗ @app.get("/todos/{todo_id}/delete")✓ @app.delete("/todos/{todo_id}", status_code=204)Tell the client what happened: 201 when created, 204 when deleted with no body.
✗ @app.post("/todos")✓ @app.post("/todos", status_code=201)/todos/latest answered 422 because /todos/{todo_id} came first. Put fixed paths first.
Sending only {"done": true} set the title to None in our test.
✗ TODOS[todo_id].update(changes.model_dump())✓ TODOS[todo_id].update(changes.model_dump(exclude_unset=True))Our 405 said "Allow: GET" although PUT and DELETE also existed on that path. Check /docs.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add PATCH /todos/{todo_id} that changes only the fields the client sends. Sending {"done": true} must keep the title. Unknown ids must give 404.
Show hintHide hint
Make a second model where every field is optional (default None), and use model_dump(exclude_unset=True) to get only the sent fields.
Show solutionHide solution
from fastapi import HTTPException
from pydantic import BaseModel
from todos import TODOS, app # the to-do app from this lesson
class TodoPatch(BaseModel): # every field optional: send only what changes
title: str | None = None
done: bool | None = None
@app.patch("/todos/{todo_id}")
def update_todo(todo_id: int, changes: TodoPatch):
if todo_id not in TODOS:
raise HTTPException(status_code=404, detail="Todo not found")
TODOS[todo_id].update(changes.model_dump(exclude_unset=True)) # only the fields that were sent
return TODOS[todo_id]
# PATCH /todos/1 {"done": true} -> {'id': 1, 'title': 'Buy milk', 'done': True}
# PATCH /todos/1 {"title": "Buy oat milk"} -> {'id': 1, 'title': 'Buy oat milk', 'done': True}
# PATCH /todos/99 {"done": true} -> 404Add GET /todos/done that returns only the finished to-dos. Make sure it works even though GET /todos/{todo_id} exists.
Show hintHide hint
Put the fixed path before the path with the parameter.
Key points
- A path operation is a method plus a path, handled by one function.
- GET reads, POST creates, PUT replaces, PATCH updates part, DELETE removes.
- Set status_code for success (201, 204); raise HTTPException for errors (404).
- 405 means "this path, but not this method"; 404 means no such path or item; 422 means bad input.
- A trailing slash gives a 307 redirect; paths are case-sensitive.
- Routes are matched in order - fixed paths before {parameters}; a duplicate route is silently ignored.
- TestClient tests the API from Python with no server.
Quick check before you move on
Interview questions
Explain the HTTP methods used in a REST API and their semantics.
GET reads (safe, idempotent), POST creates or triggers (not idempotent), PUT replaces a resource (idempotent), PATCH partially updates, DELETE removes (idempotent). Status codes reflect the outcome: 200, 201 with the new resource, 204 for no content, 404 for missing resources.
How does FastAPI match routes, and what pitfall does that create?
Routes are checked in registration order and the first match wins. A parameterised path like /items/{id} declared before /items/me captures "me" - so fixed paths must come first.
How would you implement a partial update in FastAPI?
Use a model with all fields optional and apply model_dump(exclude_unset=True) to update only the fields the client sent, returning 404 if the resource does not exist.
Quiz
- 1.
What is the difference between PUT and PATCH?
- 2.
What did GET /todos/ (with a slash) return?
- 3.
Two functions use @app.get("/hello"). Which one runs?
- 4.
Why was 404 missing from the docs for GET /todos/{todo_id}?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...