Ditch REST, go intent based
Christopher Ribeiro
Posted on January 5, 2024
At Alertpix we allow streamers to receive donations from their audience via Pix Instant Payment and show an alert on the live stream.
Our API exclusively utilizes the GET
and POST
HTTP methods. We think that we can use native features as much as we can. We bring this inspiration from the <form>
element which does not support form submissions PUT
, PATCH
, or DELETE
methods.
In this article, we explore the reasons why your API might not require more than two request methods: GET
and POST
.
REST APIs
APIs are designed for machines to communicate with each other, and there are various standards when using HTTP. The most commonly used standard is REST, which provides a great pattern for constructing APIs. If we adhere to it, we end up with a RESTful API.
However, adhering to REST often compels us to write object-oriented code and use a variety of HTTP methods. While this isn't inherently problematic, one significant drawback is that we need to structure each route for each entity in the same way:
POST /book
GET /book/:id
DELETE /book/:id
PUT /book/:id
PATCH /book/:id
If we want to add another domain we certainly will use the same route structure for it:
POST /author
GET /author/:id
DELETE /author/:id
PUT /author/:id
PATCH /author/:id
What if we need to get a book by an author? How should we do it?
GET /books/:id/author/:id
Or
GET /author/:id/books/:id
In all honesty, it's not a matter of whether it's readable or understandable; it's about the need for such complexity in the first place.
APIs are for humans
While APIs are intended for machines to consume, they are designed and utilized by humans. Human developers read the documentation and test the integration, so there's no need for excessive complexity in HTTP endpoints. Instead, we can focus on making the API more intent-based.
Going Intent-Based
Now that we understand that most of the time the integration will be done by humans. We can make it as swift as possible.
The previous example to get a book by an author can be done this way:
GET /books/by-author/:id
If you literally remove the special characters, you can read it just like an English sentence:
GET books by author id
This shift towards an intent-based approach can make API usage more intuitive and user-friendly.
Going beyond
If we want to create, edit or delete an entity, we can easily have different endpoints for that just like this:
POST /books/create {...}
POST /books/edit/:id {...}
POST /books/delete/:id
If we where in REST, editing and deleting whould be a mess. And we all know that, we often forget the difference between PATCH
and PUT
.
By going intent based we make our APIs more human readable.
This pattern is presented in our APIs and micro services so integration is always a breeze.
Posted on January 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.