Some API Design Principles

Some API Design Principles

Daily short news for you
  • Thank you to threads.net from Meta for being the inspiration behind this section on my blog. Initially, I was a bit skeptical about whether creating short posts like this would attract users, whether anyone would come back to read day after day, or if it would all just be like building sandcastles by the sea. As I have often mentioned, creating a feature is not difficult, but how to operate it effectively is what truly matters.

    Now, time has proven everything. The Short Posts section consistently ranks in the top 5 most visited pages of the day/week/month. This means that readers have developed a habit of returning more often. How can I be so sure? Because this section is almost completely unoptimized for SEO on search engines like Google.

    Let me take you back a bit. In the beginning, I was very diligent in posting on threads.net in the hope of attracting many followers, so that I could subtly introduce them to become users of my blog. However, as time went on, I increasingly felt "exhausted" because the Threads algorithm became less and less aligned with my direction. In other words, the content created was not popular.

    For example, my posts often lean towards sharing information, news, or personal experiences drawn from learning or doing something. It seems that such posts are not highly regarded and often get buried after just over... 100 views. Hmm... Could the problem be me? Knowing this, why not change the content to be more suitable for the platform?

    I have observed Threads, and the content that spreads the most easily often contains controversial elements or a prejudice about something, sometimes it’s simply stating something "naively" that they know will definitely get interactions. However, I almost do not like directing users towards this kind of content. People might call me stubborn, and I accept that. Everyone has different content directions and audiences; the choice is theirs.

    So, from then on, I mainly write here. Only occasionally, if I find something very interesting, do I go on Threads to "show off." Here, people still come to read daily; no matter who you are, I am sure that you can recognize the message I want to convey through each post. At the very least, we share a common direction regarding content. Sometimes, the scariest thing is not that no one reads what you write, but that they read it and then forget it in an instant. Quantity is important, but quality is what brings us closer together.

    Thank you all 🤓

    » Read more
  • Zed is probably the most user-centric developer community on the planet. Recently, they added an option to disable all AI features in Zed. While many others are looking to integrate deeper and do more with AI Agents. Truly a bold move 🤔

    You Can Now Disable All AI Features in Zed

    » Read more
  • Today I have tried to walk a full 8k steps in one session to show you all. As expected, the time spent walking reached over 1 hour and the distance was around 6km 🤓

    Oh, in a few days it will be the end of the month, which means it will also mark one month since I started the habit of walking every day with the goal of 8k steps. At the beginning of next month, I will summarize and see how it goes.

    » Read more

The Problem

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!

Some Principles

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.

Path Rules

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.

Method Rules

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.
...

Response Status Code Rules

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.

Response Body Rules

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:

API design.

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (1)

Leave a comment...
Avatar
Tiennx Business1 year ago

bài viết hay quá anh Hoài. Mà e nghĩ những từ cần chú ý "keyword" vd như: 401,400,500,... thì nên đổi màu cho nổi để dễ nhìn :D

Reply
Avatar
Xuân Hoài Tống1 year ago

Ok luôn, a cũng thấy hơi lấn cấn 😅