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

Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat

Send PUT, DELETE and POST twice to a FastAPI Book API and watch the database: PUT and DELETE leave the same result, POST makes a second Matilda. Then links in answers (HATEOAS) and the four maturity levels.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Explain why a client sends the same request twice when an answer gets lost
  • Show what PUT, DELETE and POST do when they are repeated, from the database side
  • Tell safe from idempotent methods with a two-question table
  • Place an API on the four REST maturity levels, and explain what HATEOAS adds

Before you start

  • RESTful API Basics
  • FastAPI routes for POST, PUT and DELETE

You press the lift button, then you press it again. A second lift doesn't come. Now picture a button that orders a pizza. Press it twice and two pizzas arrive.

HTTP requests behave like one of those two buttons. Some can be sent again and nothing changes. Others create a second copy of something every time. This article sends the same requests twice to a small FastAPI Book API and looks at what the database does each time. After that we look at links inside an answer (HATEOAS) and at how much of REST an API uses, the maturity levels.

Why a client sends the same request twice

A client sends PUT /api/books/11 to change the book Mort. The server changes it and starts sending the answer back, and the answer gets lost on the way: a dropped mobile connection, a timeout, a proxy that gave up.

The client now has no idea whether the change happened. So it does the only sensible thing and sends the very same request again. This time the answer arrives. The question is whether that second request was safe.

The client sends PUT /api/books/11. The server answers 200 but the answer is lost. The client is not sure it arrived, so it sends the same PUT again and this time gets the 200. Client Book API PUT /api/books/11 200 lost same PUT again 200 arrives
A client that isn't sure the first request worked will send it again.

The routes we're testing

This is the Book API from the REST section: FastAPI, SQLAlchemy and an in-memory SQLite database with echo=True, so every SQL statement gets printed. These are the three write routes from library/routers/books.py:

@router.post("", response_model=BookResponse, status_code=201, summary="Add a book", operation_id="create")
def add_book(book: BookRequest, response: Response, service: BookService = Depends(get_service)):
    saved = service.create(models.Book(**book.model_dump()))
    response.headers["Location"] = f"/api/books/{saved.id}"
    return saved


@router.put("/{book_id}", response_model=BookResponse, summary="Replace a book", operation_id="replace")
def replace_book(book_id: int, book: BookRequest, service: BookService = Depends(get_service)):
    return service.replace(book_id, models.Book(**book.model_dump()))


@router.delete("/{book_id}", status_code=204, response_class=Response, summary="Remove a book", operation_id="delete")
def delete_book(book_id: int, service: BookService = Depends(get_service)) -> None:
    service.delete(book_id)

The service in library/services/book_service.py does the work. replace copies the new values onto the stored book. delete looks the book up first, and the lookup raises BookNotFound (a 404) when the id isn't there:

    def get(self, book_id: int) -> Book:
        book = self.repository.find_by_id(book_id)
        if book is None:
            raise BookNotFound(book_id)
        return book

    def create(self, book: Book) -> Book:
        return self.repository.save(book)

    def replace(self, book_id: int, changes: Book) -> Book:
        book = self.get(book_id)
        book.title, book.author, book.pages = changes.title, changes.author, changes.pages
        return self.repository.save(book)

    def delete(self, book_id: int) -> None:
        self.repository.delete(self.get(book_id))

Keep that code in mind. The difference between the three methods comes straight out of it.

PUT twice: the same book

Mort has 272 pages in the database. We send this request twice:

PUT /api/books/11 HTTP/1.1
{"title": "Mort", "author": "Terry Pratchett", "pages": 280}

Both answers are identical:

HTTP/1.1 200
{"id":11,"title":"Mort","author":"Terry Pratchett","pages":280}

The database tells the rest of the story. The first request runs an update:

UPDATE book SET pages=? WHERE book.id = ?
-- parameters: (280, 11)

The second request runs no UPDATE at all. The book already says 280 pages, so SQLAlchemy finds nothing to change. Pages went 272, then 280, then stayed at 280. Sending the same PUT twice leaves the same book.

DELETE twice: still gone

Now we delete book 7, then send the very same request again.

DELETE /api/books/7 HTTP/1.1

The first answer is 204, no content. The second one is different:

HTTP/1.1 404
Content-Type: application/problem+json
{"detail":"No book with id 7","instance":"/api/books/7","status":404,"title":"Book not found"}

In the database, the first request runs DELETE FROM book WHERE book.id = ? with (7,). The second finds nothing, so it deletes nothing. After the first request book 7 is gone, and after the second it is still gone.

This trips people up. The answer changed, 204 and then 404. But idempotence is about the state of the server, not the status code, and the server ends up exactly the same.

POST twice: two Matildas

Last, we add a book and send the same request again:

POST /api/books HTTP/1.1
{"title": "Matilda", "author": "Roald Dahl", "pages": 240}
HTTP/1.1 201
Location: /api/books/13
{"id":13,"title":"Matilda","author":"Roald Dahl","pages":240}

HTTP/1.1 201
Location: /api/books/14
{"id":14,"title":"Matilda","author":"Roald Dahl","pages":240}

Each request ran its own INSERT INTO book (title, author, pages, shelf_code) VALUES (?, ?, ?, ?). Now the library has book 13 and book 14, both called Matilda. That's the pizza button: repeat a POST and you get a second copy.

Safe and idempotent, in one table

Two questions for each method. Does it only read? And if you repeat it, is the result the same?

MethodOnly readsSame result if repeatedWhat we saw
GETyesyes200, no write
PUTnoyes200, 200
DELETEnoyes204, 404
POSTnono201, 201

A method that only reads is called safe. A method you can repeat and still end with the same result is called idempotent. GET is both. PUT and DELETE write, but they are idempotent. POST is neither, so a client (or a retry library) must be careful about sending it twice.

PUT is idempotent here because it replaces the book with the full set of values the client sent. The request says "book 11 should look like this", and saying it twice doesn't change what it should look like. POST says "add a book", and two of those add two books.

HATEOAS: links in the answer

Think about a web page. It shows links, like Home, Books and Contact. You click one and go where it leads, and nobody had to hand you a manual first.

An API answer can work the same way. Along with the data, it can list what the client can do next: see this book, see all books, change it. The idea has a long name, Hypermedia As The Engine Of Application State, shortened to HATEOAS.

Our Book API doesn't do this. Here is its real answer for book 2:

GET /api/books/2
{"id":2,"title":"Dune","author":"Frank Herbert","pages":412}

Data, and no links. An answer with links could look like the one below. This is only an example; our API doesn't send it:

{"id":2,"title":"Dune",
 "links":[
   {"rel":"self","href":"/api/books/2"},
   {"rel":"books","href":"/api/books"}
 ]}

Each link has a name (rel) and an address (href), and the client follows a link to move on. Our API tells clients what exists in a different way, through the contract at GET /openapi.json, which Swagger UI reads at /docs. Links in the answer or a contract in the docs: both tell the client what it can call.

The four maturity levels

How much of REST does an API actually use? There are four levels, usually called the Richardson maturity model.

Four rising steps. Level 0: one URL, one method. Level 1: one URL per thing, like /api/books/2. Level 2: the right methods and status codes; the Book API is here. Level 3: links in the answers, HATEOAS. Level 0 one URL, one method Level 1 one URL per thing /api/books/2 Level 2 methods and status codes Book API Level 3 links in the answers (HATEOAS)
The Book API uses separate URLs, the right methods and the right status codes, so it sits on level 2.
  • Level 0: one URL and one method. Every call goes through the same door.
  • Level 1: a separate URL for each thing, like /api/books/2.
  • Level 2: the right method for each action and the right status code for each result: PUT, DELETE, 201, 204, 404. Our Book API is here.
  • Level 3: links in the answers, which is HATEOAS. Our API doesn't go this far.

Level 2 with a published OpenAPI contract is where this section's Book API ends up, and the contract does the job of telling clients what exists.

Common mistakes

  • Treating "same status code" as the test. DELETE answered 204 and then 404, and it is still idempotent. Look at what the server holds afterwards.
  • Retrying POST blindly. An automatic retry on a lost answer turned one Matilda into two. Retry GET, PUT and DELETE freely; think before repeating a POST.
  • Using PUT for a partial change. PUT replaces the whole book with what the client sends, and that full replacement is what makes it repeatable. Our BookRequest requires title, author and pages for exactly this reason.
  • Calling an API "not REST" because it has no links. Level 2 is a normal, honest place to be. Just know which level you're at.

Recap

IdeaWhat to remember
IdempotentRepeat it and the server ends up the same: GET, PUT, DELETE
POSTEvery repeat adds a new row (id 13, then 14)
SafeOnly reads: GET
HATEOASLinks in the answer say what the client can do next
Maturity level 2Separate URLs, right methods, right status codes: the Book API

For the basics of each method, see RESTful API Basics. Try it yourself: send the "Delete a book" request in the project's requests.http file twice, then send "Add a book" twice and list the books to count the Matildas.

Keep going in FastAPI · 14 of 26

Previous
API Versioning in FastAPI with an API-Version Header
Next post
A FastAPI REST API End to End: One App Visit, Seven Requests
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)

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

  • Why a client sends the same request twice
  • The routes we're testing
  • PUT twice: the same book
  • DELETE twice: still gone
  • POST twice: two Matildas
  • Safe and idempotent, in one table
  • HATEOAS: links in the answer
  • The four maturity levels
  • Common mistakes
  • Recap
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.