In the previous text, we familiarize ourselves with the concept of the idempotent methods in HTTP.
Let’s talk about safe methods today. What does it mean? Does it have something to do with HTTPS? Well, not really 😉
Let me explain it.
Definition
Let’s take a look for the docs definition:
Request methods are considered “safe” if their defined semantics are
essentially read-only
In other words, our client (browser, mobile app, smart-refrigerator, or anything else) shouldn’t expect any state change on the server as a result of the request.
By using a safe method you shouldn’t expect any losses, harms, or other unusual behavior on the server.
Safe methods can be cached or prefetched too and these actions shouldn’t change the state of the resource.
Methods
Following methods are considered safe:
-
- GET
- HEAD
- OPTIONS
- TRACE
Example
Calling a safe method shouldn’t change the state of the resource:
-
- GET /items/1
We expect it to return the item with id 1. Regardless of how many times we decide to perform this call, the item won’t change (there won’t be any modifications or side-effects).
That’s why GET is considered to be a safe method.
On the other hand, a non-safe method, such as POST, may change the state of the resource:
-
- POST /item
POST is neither safe nor idempotent, so we can’t really predict what will happen. That’s why POST isn’t considered to be a safe method.
Why should we bother?
In my opinion, we should think about methods safety (and idempotence at the same time) when we’re designing our APIs.
Following good principles makes our contract much more clear. Just because it relies on good API design standards. And if the API has a clean and easy to follow the design, it simply boosts the trust of your end-clients.
Stay safe 👋