PUT POST PATCH DELETE GET

When considering using PUT or POST or PATCH in an API, we're talking about a concept of Idempotent

Non-idempotent (POST, GET)

Non-idempotent means if you apply the same method (POST), the result might change over time.

For example,

  • Uploading new file in google drive is non-idempotent.
    • You can re-upload the same file multiple times, it will just create new copy of the file.
  • Creating a blog post is POST
    • You can create the same blog of the same content multiple times, it will just create a new blogs.
  • Signing up an user is POST
    • Signing up is a special case, since you cannot sign up multiple time because of business logic.
    • However, imagine a business allow of multiple sign up, the next time you sign up using the same email and different password shouldn't replace the original password. Therefore it should be non-idempotent.
  • Login is POST
    • You can login multiple time, every single time there is a different session for your login. Therefore it's POST.

For GET it's quite obvious because the next time you do get again the result might have been updated already

Idempotent (PUT, PATCH, DELETE)

For DELETE it makes sense to use out of the box but PUT and PATCH normally caused misconception.

Diference between PUT and PATCH

PUT and PATCH request are Idempotent, which means multiple call of PUT or PATCH should result in the same state.

However:

  • Calling PUT means replacing everything.
  • Wheras calling PATCH means to update only that thing .

For example, to update the email address of an user, we need to call the following

If we have

PUT /users/1
{
	"username": "rockmanvx6",
	"email": "[email protected]"
}

versus a PATCH request which we only needs to specify the email only

PATCH /users/1
{
	"email": "[email protected]"
}

What happen if you just call PUT with the updated field only?

PUT /users/1
{
	"email": "[email protected]"
}

If that so when we GET the user, the user will be

GET /users/1
{
	"email": "[email protected]"
}

Which will replace the whole user objects.

[!note]
Note that this also depends on the serverside implementation, but this is the standard.