How to design an API-Best practices-Part 2
If you have already read part 1 of this article, you may know most of the basic things about APIs. If you have not, please read it and come to this part. However, I will give you a brief introduction to APIs here as well.
What is an API ?
Technically, API stands for Application Programming Interface. It is a set of protocols, routines, and tools to build applications. We can say API makes the connection between the user and the system. That means API is the messenger. It takes requests from the user and brings them to the system for some kind of action to be performed. Otherwise, we can say, API specifies how should interact software components with each other. As well as
How to design an API ?
When you start to design an APIs there several parts need to be considered. Otherwise, your APIs will not be up to standards. And these will help you to optimize your APIs and reduce the response time. Ok...Let’s see one by one what are these best practices.
Name the API properly
We should not use verbs as API paths. Instead, we should use nouns that represent the entity that the endpoint that we’re retrieving or manipulating as the pathname.
Consider developing an API that sends you information about a specific user. Simply naming the API ‘GetUsers ’wouldn’t be a good idea since it implies that you want to retrieve every user in the database, and the external user calling the API would be expecting a result from what you intend to offer.
Let the action to be decided by the HTTP methods. Think we are dealing with articles. If we create API to retrieve articles we can create routes like GET /article, and create a new article we can create like POST /article. If we want to update use like PUT /article:id and for deleting use DELETE /article:id.
- Use a clear concise name:
It makes no sense to name the API “api/animal/” if you want to query a database of cats. A cat is an animal, but the end consumer doesn’t desire it. Name it “api/cats/” since the end user wants a specific animal.
- Use the exact words that explain the query properly
“api/stationery/pens”. This explains the API queries for all pens in the stationery database. But don’t use it as “api/stationery/write”.
- Do not use special characters
Using special fancy characters in the API will confuse the user like “api/animal%20?/cat”. They won’t understand the functions of this API, how it makes queries, or the data it will obtain.
Define parameters when necessary
Try to avoid using parameters as much as you can. If it is must to use, then it’s okay to use. There are places you have to use parameters in your APIs you can not avoid like :
- Request headers and cookies: This parameter uses a small piece of data that a server sends to a user’s web browser.
- URL query string: These parameter elements are inserted in your URLs to help you filter and organize content or track information on your website.
- URL paths: This is a required parameter that gives the end-user or whoever calls the API a way to get the right information, such as: “/users/<user_id>/”.
- Body query string/multipart: This parameter sets the HTTP method for the question or API, such as POST — for sending data, or PUT — for updating the data in an API.
Define response object
With the belief of the response object doesn’t want to change if the user requests additional information, many developers generate a response object that includes every piece of data from the API service, even unused data.
Unfortunately, this is a poor method for designing APIs. It is important to just return the information that the external user will require when creating a response object because developing a huge microservice will have an impact on performance and more.
JSON is the standard for transferring data. Almost every networked technology can use it. Server-side technologies have libraries that can decode JSON without doing much work. Here are some response objects.
- Title: If the object is returning user information, the title of the response will appear as User. This is a response object that is required.
- Subject: The response’s subject includes the user and any other user-related data that the API is intended to relate.
- Sender_id: The sender’s or user’s generated ID. This is an optional response object, so you may decide not to include it if it is not required.
- Categories: This describes the response object’s category. The category will be Users if the API provides a user’s data.
Define the error object and return standard error codes
This is an important part that you need to look at closely. If an error occurs when an external user queries the database, the error message should be clear and concise. It is not just enough to say “error found” or “error occurred”. The title of the response should be this, and the data or subject part should describe the type of mistake that occurred. And it is important to return unnecessary details.
Let’s think the user has not entered the password length correctly. Do not return an error message like this:
message: "Password should contain at least 8 characters"
Instead of that, you can do it like this:
message: "Wrong Password length. Try again",
This clarifies what the end user did incorrectly, and the formatting makes it clear to the end user that this issue was caused by the client. And don’t forget to mention the HTTP status code correctly. Here are some common error HTTP status codes:
- 400 Bad Request — This means that client-side input fails validation.
- 401 Unauthorized — This means the user isn’t not authorized to access a resource. It usually returns when the user isn’t authenticated.
- 403 Forbidden — This means the user is authenticated, but it’s not allowed to access a resource.
- 404 Not Found — This indicates that a resource is not found.
- 500 Internal server error — This is a generic server error. It probably shouldn’t be thrown explicitly.
- 502 Bad Gateway — This indicates an invalid response from an upstream server.
- 503 Service Unavailable — This indicates that something unexpected happened on the server side (It can be anything like server overload, some parts of the system failed, etc.).
Use correct HTTP methods
When we select an HTTP method for our APIs it’s an important factor you need to consider. You must use the correct method to let users query the right way. These are the most common HTTP methods used:
- POST: Use this method if the end-user is to send data to the API.
- GET: Use this method if the end-user is to retrieve data after the API queries the database.
- PUT: Use this method if the end-user updates existing data in the database.
- PATCH: Use this method if the end-user needs to correct or replace existing data in the database.
- DELETE: Use this method if the end-user deletes any information or data from the database.
Imagine that the API function you created utilizes the POST method. And think external user wishes to query the user database by supplying an ID. This will restrict users’ queries because they aren’t updating or creating new data, and they aren’t able to query as they are able to. It would be ideal to use the GET method and pass an ID as a parameter.
This is the end of our article. We have discussed several best practices you have to follow when you create APIs. Hope this will be helpful for you.
See you in the next blog post. Bye Bye🍻🍸❤️❤️