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.
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 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?
| Method | Only reads | Same result if repeated | What we saw |
|---|---|---|---|
| GET | yes | yes | 200, no write |
| PUT | no | yes | 200, 200 |
| DELETE | no | yes | 204, 404 |
| POST | no | no | 201, 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.
- 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
BookRequestrequires 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
| Idea | What to remember |
|---|---|
| Idempotent | Repeat it and the server ends up the same: GET, PUT, DELETE |
| POST | Every repeat adds a new row (id 13, then 14) |
| Safe | Only reads: GET |
| HATEOAS | Links in the answer say what the client can do next |
| Maturity level 2 | Separate 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.
StudyEasy AI Community
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
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.
