POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
Add, change and remove books in a FastAPI Book API. Where 201 and the Location header come from, why PUT answers 200, how DELETE answers 204 with no body, and one helper that turns a missing id into 404.
What you will learn
- Write POST, PUT and DELETE routes for a resource in FastAPI
- Return 201 with a Location header from status_code and the Response object
- Answer 204 with no body using response_class=Response
- Raise HTTPException 404 from one helper shared by several routes
Before you start
- HTTP methods and status codes from the client side
- A FastAPI GET route with a Pydantic model
Reading books is easy: the client sends a GET and the books come back. But how does a client add a book, change one or remove one? And how does your FastAPI route decide which status code to answer with?
The client side of methods and status codes is covered in RESTful API basics. This article is the server side. We use a small Book API with three books in a list: The Hobbit, Dune and Emma, all under /api/books.
The same address, four verbs
| Method | Address | Does | Answers |
|---|---|---|---|
| GET | /api/books, /api/books/{id} | reads | 200 |
| POST | /api/books | adds a book | 201 + Location |
| PUT | /api/books/{id} | replaces a book | 200 |
| DELETE | /api/books/{id} | removes a book | 204 |
The data
The model, in library/schemas.py. The id is optional because the server gives it:
class Book(BaseModel):
id: int | None = None # the server gives the id, the client does not send one
title: str
author: str
pages: int
And the shelf, in library/routers/books.py:
from itertools import count
from fastapi import APIRouter, HTTPException, Response
from library.schemas import Book
router = APIRouter(prefix="/api/books", tags=["Books"])
books = [
Book(id=1, title="The Hobbit", author="J.R.R. Tolkien", pages=310),
Book(id=2, title="Dune", author="Frank Herbert", pages=412),
Book(id=3, title="Emma", author="Jane Austen", pages=474),
]
next_id = count(4) # 4, 5, 6 ... a number is never used twice
next_id is a counter that starts at 4. Each new book takes the next number.
POST adds a book: 201 and Location
@router.post("", status_code=201, summary="Add a book", operation_id="create")
def add_book(new: Book, response: Response) -> Book:
book = Book(id=next(next_id), title=new.title, author=new.author, pages=new.pages)
books.append(book)
response.headers["Location"] = f"/api/books/{book.id}"
return book
The answer has three parts, and each has its place in the code:
- Status:
status_code=201on the decorator. 201 means Created. - Header:
response.headers["Location"], set on theResponseobject FastAPI passes in, with an address built from the new id. - Body: whatever we return. FastAPI turns the book into JSON.
The client sends Matilda with no id:
POST http://localhost:8080/api/books
Content-Type: application/json
{"title": "Matilda", "author": "Roald Dahl", "pages": 240}
The recorded answer: status 201, header Location: /api/books/4, and this body:
{"id":4,"title":"Matilda","author":"Roald Dahl","pages":240}
Matilda is book 4, and the counter moves on to 5. The Location header tells the client where the new book lives.
PUT replaces a book: 200
@router.put("/{book_id}", summary="Replace a book", operation_id="replace")
def replace_book(book_id: int, changes: Book) -> Book:
old = find_book(book_id)
book = Book(id=book_id, title=changes.title, author=changes.author, pages=changes.pages)
books[books.index(old)] = book
return book
PUT sends the whole book: title, author and pages. The id comes from the address, not the body. There's no status_code on the decorator, so a plain return answers 200:
PUT http://localhost:8080/api/books/2
Content-Type: application/json
{"title": "Dune Messiah", "author": "Frank Herbert", "pages": 256}
{"id":2,"title":"Dune Messiah","author":"Frank Herbert","pages":256}
Same id, new content.
DELETE removes a book: 204
@router.delete("/{book_id}", status_code=204, response_class=Response, summary="Remove a book", operation_id="delete")
def delete_book(book_id: int) -> None:
books.remove(find_book(book_id))
DELETE /api/books/3 has no body, and the answer is 204 No Content: done, and nothing to send back. response_class=Response makes FastAPI send a plain empty response instead of trying to write JSON. In the recorded run, the 204 had no headers and 0 bytes of body.
Send the very same DELETE again. Book 3 is gone, so the answer is 404:
{"detail":"Book not found"}
No such id? One helper, 404 everywhere
def find_book(book_id: int) -> Book:
for book in books:
if book.id == book_id:
return book
raise HTTPException(status_code=404, detail="Book not found")
If the loop ends without a match, the last line raises HTTPException with 404. The GET-one route, the PUT route and the DELETE route all call this helper, so all three answer a missing id the same way. A PUT for book 99 shows it:
PUT http://localhost:8080/api/books/99
Content-Type: application/json
{"title": "Ghost", "author": "Nobody", "pages": 1}
Answer: 404, {"detail":"Book not found"}.
Every change shows up in the next GET
The full recorded run, from the server log:
INFO: 127.0.0.1:49275 - "GET /api/books HTTP/1.1" 200 OK
INFO: 127.0.0.1:49276 - "GET /api/books/2 HTTP/1.1" 200 OK
INFO: 127.0.0.1:49277 - "GET /api/books/99 HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:49278 - "POST /api/books HTTP/1.1" 201 Created
INFO: 127.0.0.1:49279 - "PUT /api/books/2 HTTP/1.1" 200 OK
INFO: 127.0.0.1:49280 - "PUT /api/books/99 HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:49281 - "DELETE /api/books/3 HTTP/1.1" 204 No Content
INFO: 127.0.0.1:49282 - "DELETE /api/books/3 HTTP/1.1" 404 Not Found
INFO: 127.0.0.1:49283 - "GET /api/books HTTP/1.1" 200 OK
The last GET returned:
[{"id":1,"title":"The Hobbit","author":"J.R.R. Tolkien","pages":310},{"id":2,"title":"Dune Messiah","author":"Frank Herbert","pages":256},{"id":4,"title":"Matilda","author":"Roald Dahl","pages":240}]
Emma is gone, and id 3 isn't reused: Matilda keeps 4. One note: the books live in a list in memory, so they last only while the app runs. Moving them into a database is the next step, in from a list to a database.
Run it
pip install -r requirements.txt
uvicorn library.main:app --reload --port 8080
Then send the requests in requests.http one by one, or use Swagger UI at http://localhost:8080/docs.
Common mistakes
- Letting the client send the id on POST. The server picks it; the model makes
idoptional for that reason. - Returning a body with 204. 204 means no content. Use
response_class=Responseand return nothing. - Copying the 404 check into every route. One helper keeps every route consistent.
- Forgetting the Location header on 201. The client then has to guess where the new book lives.
Quick recap
| Method | Code | Status |
|---|---|---|
| POST | status_code=201, response.headers["Location"] | 201 Created |
| PUT | plain return | 200 OK |
| DELETE | status_code=204, response_class=Response | 204 No Content |
| missing id | raise HTTPException(status_code=404, ...) | 404 Not Found |
The method says what to do; the status says what happened.
Try it yourself
Add a book, then delete it twice and add another. Check the ids in the next GET, and explain why no number is ever used twice.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.
RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
