When developing software, there are design patterns that should or even need to be followed to help everyone in the team understand and collaborate smoothly. "Design patterns" are the clearest evidence for easier understanding when we all think the same way.
API design is the same, creating dozens of endpoints in a period of time is quite easy, but maintaining consistency throughout the development process is difficult. Projects evolve over time, people change, the more minds participate in the process, the more personalities are expressed through lines of code.
The truth is, API design depends on the creativity of each individual, organization. If a group is not strict enough with the issue of naming an endpoint, then this world is yours, feel free to be creative based on what you can think of. Conversely, some organizations impose strict rules in this process, forcing us to comply. But no matter what, the ultimate goal of that is to make sure that the majority of programmers can understand or know how to find what they need.
I am a person who likes creativity, but there are things that I still need to adhere to in order to ensure the transparency of the API. In this article today, I will present some principles in the API Design process that many programmers around the world are applying. If you don't believe it, after reading this article, try to "explore" an API set from any 3rd party providing Cloudflare to see what they are doing.
Once again, the rules mentioned below are for reference only and are not mandatory for anyone to follow. If you realize the benefits of adhering to the principles, I believe that this is something not to be overlooked. Without further ado, let's get to work!
First, let's clarify some concepts related to API design.
We have resources, representing the "resources" we want to access or perform an operation on. When calling an endpoint, data is returned, which can be a list of articles, article details... collectively called resources. Additionally, resources often have attributes, which are a component of the resource or are computed based on the resource.
A collection is a set of resources, usually resources of the same type are grouped into a collection. For example, for a resource like "Users", we have a collection of operations with users such as add, edit, delete... called Collections.
URLs, well, they point to your resource. For example, /articles
to refer to the list of articles.
Define a collection for the resource, for example, /articles
for articles, /comments
for comments, and always use plural nouns.
Use "kebab-case" for everything in the URL path, and "camelCase" for query parameters. For example, /special-articles?isHighlight=true
.
Use "identifier code", such as the ID of the resource, to interact with a specific resource. For example: /articles/nodejs-la-gi
to interact with the article with the URL "nodejs-la-gi".
Avoid using paths that contain attributes of the resource or actions on the resource, as it will cause confusion and complicate the path later on. For example, avoid /articles/nodejs-la-gi/summary
or /articles/nodejs-la-gi/reset-view
, try moving the attribute to parameters or in the request body, for example /articles/nodejs-la-gi?summary=true
.
Specify a prefix for the API version, for example /v1/articles
to point to version 1 of the API. If the API is later upgraded, we can expand with /v2
, /v3
... without affecting previous versions.
There are 5 common HTTP methods that we have all heard of.
GET: To retrieve a resource.
POST: To create a new resource.
PUT: To update existing resources.
PATCH: To update existing resources, but only update the provided fields, leave the others as they are.
DELETE: To delete existing resources.
Combined with the path rules, the HTTP methods contribute to clarify the action you want to perform on the resource. For example:
GET /articles - get a list of all articles.
GET /articles/nodejs-la-gi - get the article details with the URL nodejs-la-gi.
POST /articles - create a new article.
DELETE /articles - delete an article.
...
HTTP response status codes are numbers that indicate whether an HTTP request is successful or not.
There are many status codes, but below are some numbers that we often encounter:
200 OK: The request was successful.
201 Created: Typically returned when the API has just successfully created a new resource.
204 No Content: The operation was successful but no data is returned, for example, when deleting an existing resource.
400 Bad Request: Indicates an error when the request is invalid or contains invalid data, so processing should be rejected.
401 Unauthorized: Indicates an error when this request requires valid credentials before processing, such as not being logged into the system.
403 Forbidden: Indicates an error when the user does not have permission to perform this function.
404 Not Found: Indicates an error when the requested resource or action is not found.
500 Internal Server Error: An "undefined" error from the server, which may be the result of unintended incidents such as hardware, software, network errors...
In addition, you can refer to other error codes at HTTP response status codes - Mozilla. Adhering to status codes helps achieve consistency in the development process, as well as for integrating parties.
Keep your response body consistent from start to finish. For example, a successful response includes the response code, message, and returned data.
{
"status": 200,
"message": "OK",
"data": {
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
}
If it is an error message, include the error code and error message.
{
"code": 400,
"message": "Bad Request"
}
Keep error messages as generic as possible to limit the disclosure of data or other important information.
There are also a few other rules in API design, such as:
Always paginate requests to list resources, for example, /articles?limit=10&offset=0
or /articles?page=1&limit=10
... If possible, return the total number of resources in that list. List resources may also need to be sorted in a certain order, for example, /articles?sort=createdAt:desc
...
Detail resources usually return all possible attributes, but that is not always necessary. It can support the retrieval of specific attributes through filtering, for example /articles?field=url,title,content,createdAt
...
References:
Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.
Comments (1)