Member-only story
Why You Should Use a PUT Request Instead of a POST request
And how you can easily create one in FastAPI
I’ve received this question a dozen times: Why do you use a PUT request instead of a POST request?
At the end of this article, you will understand why. You’ll implement it in Python with FastAPI, and you’ll learn how to test it properly as well so you’ll be comfortable using it in practice.
The Difference Between a PUT and POST Request
Let’s start by explaining the critical characteristic of a PUT request: idempotency.
If you were to call a put request multiple times, it would lead to the same result. So, imagine you create a resource: a book. If you call that method twice, the result is the same. More precisely, one book exists in the database. Not multiple, one.
A POST request is quite different. If you create one book and then create the same book afterward, you would have multiple books. Or, in other words — the second time, you get a different result.
Both methods have their advantages. The PUT request is handy to prevent side effects.
But, to give you a better idea, let me explain a scenario: Juliette clicks on a button to purchase a sandwich. Because the webshop is a bit slow, she presses the same button once more. The same request reaches the server twice. Because you have implemented the method with a put request, it has no effect the second time it hits the server. You prevent Juliette from having to eat a double meal, and you save her money. Great, isn’t it?
In many use cases, a PUT request is extraordinary to prevent unneeded updates.
Note: Be careful, you can still violate idempotency even if you use the PUT method. If you implement a PUT request in the same way as a POST request, it will be the same, violating the PUT principle. You, as an API developer, are responsible for creating a valid PUT request.
How To Create a PUT Request
First, set up your Python environment. You’ll need a few libraries to do so: FastAPI, uvicorn, pydantic, and requests. Feel free to install them with your tool of choice—my personal…