Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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

MethodAddressDoesAnswers
GET/api/books, /api/books/{id}reads200
POST/api/booksadds a book201 + Location
PUT/api/books/{id}replaces a book200
DELETE/api/books/{id}removes a book204

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=201 on the decorator. 201 means Created.
  • Header: response.headers["Location"], set on the Response object 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"}.

Five pieces of code and the status each gives: a plain return gives 200; status_code=201 gives 201 with a Location header; a PUT route with no status_code gives 200; status_code=204 with response_class=Response gives 204 with no body; raise HTTPException(404) gives 404. return books @router.post(..., status_code=201) @router.put(...) # no status_code status_code=204, response_class=Response raise HTTPException(status_code=404) 200 OK 201 + Location 200 OK 204, no body 404 Not Found
We choose the status in code. The client reads it first.

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 id optional for that reason.
  • Returning a body with 204. 204 means no content. Use response_class=Response and 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

MethodCodeStatus
POSTstatus_code=201, response.headers["Location"]201 Created
PUTplain return200 OK
DELETEstatus_code=204, response_class=Response204 No Content
missing idraise 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 11 of 26

Previous
Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
Next post
Paging, Sorting and Filtering a REST API in FastAPI

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.

On this page

  • The same address, four verbs
  • The data
  • POST adds a book: 201 and Location
  • PUT replaces a book: 200
  • DELETE removes a book: 204
  • No such id? One helper, 404 everywhere
  • Every change shows up in the next GET
  • Run it
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.