RESTful API: Design guidelines – The best practices

Tram Ho

Facebook, Google, GitHub, Netflix and a few other tech giants have given developers and products the opportunity to use their data through APIs and become their platform.

Even if you do not write APIs for developers and other products, it is always good for your application to be able to manually create a beautiful API.

There is a lingering debate on the internet about the best ways to design APIs and that is one of the best nuances. No official guidelines have been identified.

The API is an interface through which many developers interact with data. A well-designed API is always very easy to use and makes the developer life very smooth.

The API is a GUI for developers, and if it’s confusing or cumbersome, developers will start to find alternatives or stop using it. The experience of developers is the most important measure of the quality of APIs.

The API is like an entertainer performing on stage and its users are audience.

Terminologies

The following are the most important terms regarding REST APIs.

  • A resource is an object or representation of something that has some data associated with it and may have a set of methods to operate on it. For example. Animals, schools and staff are resources and deletion, additions and updates are the activities performed on these resources.
  • Collection is a collection of resouces, for example, a company is a collection of company resources.
  • The URL (Uniform Resource Locator) is a path through which resources can be located and actions can be taken on them.

Endpoint API

Write a few APIs for a company with a few employees to understand more:

/getAllEmployees is an API that will respond to the employee list. A few more APIs around a company would look like this:

  • /addNewEmployee
  • /updateEmployee
  • /deleteEmployee
  • /deleteAllEmployees
  • /promoteEmployee
  • /promoteAllEmployees

And there will be tons of other endpoint APIs like this for different operations. All of which will contain redundant actions. Therefore, all these API endpoints will be very heavy to maintain as the number of APIs increases.

What is wrong?

The URL should only contain sources (nouns), not actions or verbs. The API //addNewEmployee contains the addNew action along with the resource name Employee .

What is the correct way?

/companies endpoint is a good example because it contains no action. But the question is: How do we tell the server about the action is performed on the resource of companies and whether to add, delete or update?

This is where HTTP methods ( GET , POST , DELETE , PUT ), also known as verbs, play a role.

The resource must always be in the plural form in the API endpoint and if we want to access an instance of the resource, we can always pass the ID in the URL.

  • The GET method /companies will get a list of all companies.
  • Method GET path /companies/34 will receive details of the company 34.
  • DELETE method path /companies/34 to delete the company 34.

In some other use cases, if we had resources in a resource, for example, employees of a company, some sample API enpoint would be:

  • GET /companies/3/employees should get a list of all employees from company 3.
  • GET /companies/3/employees/45 should get details about employee 45, who belongs to company 3.
  • DELETE /companies/3/employees/45 should delete employee 45, person of company 3.
  • POST /companies should create a new company and return details of the newly created company.

Is our API now more accurate and consistent?

HTTP Methods (Verbs)

HTTP has defined several methods that indicate the type of action to be performed on resources.

The URL is a sentence where resource is noun and HTTP method is verb.

Important HTTP methods are as follows:

  1. GET method requests data from the resource and doesn’t make any other impact. For example: /companies/3/employees returns a list of all employees from company 3.
  2. POST method request server creates resources in the database, mostly when a webform is sumitted. For example: /companies/3/employees creates a new employee of the company 3. POST is non- idempotent , which means that many requests will have different effects.
  3. PUT method request server updates the resource or creates it if it does not exist. For example. /companies/3/employees/john will request the server to update or create if it does not exist, john resources in the staff of company 3. PUT is idempotent , which means that many requests will have the same effect.
  4. DELETE method requests resources, or their instances, are deleted from the database. For example: /companies/3/employees/john/ will request the server to remove john resources from the staff of company 3.

There are a few other methods that we will discuss in another article.

HTTP Response Status Codes

When the client issues a request to the server via the API, the client should receive a response, whether it is corrupted, passed or the request is wrong.

HTTP status codes are a series of standardized codes that have different interpretations in different situations. The server must always return the correct status code.

The following are important categories of HTTP codes:

2xx (Success Category)

These status codes indicate that the requested action has been successfully received and processed by the server.

  • 200 OK – standard HTTP response shows success for GET , PUT or POST .
  • 201 Created – This status code must be returned whenever a new instance is created. For example. When creating a new instance, using the POST method, will always return status code 201.
  • 204 No Content – The query instance was successfully processed but has not returned any content yet. DELETE may be a good example of this. API DELETE /companies/43/employees/2 will delete employee 2 and in return, we don’t need any data in API response part, because we explicitly requested the system to delete. If there are any errors, such as if employee 2 does not exist in the database, the response code will not belong to the 2xx Success Category but to the 4xx Client Error category .

3xx (Redirection Category)

  • 304 Not Modified – Indicates that the client has a response in its cache. And so there is no need to transfer the same data again.

4xx (Client Error Category)

These status codes indicate that the client has issued a faulty request.

  • 400 Bad Request – Indicates that the client request was not processed, because the server cannot understand what the client is requesting.
  • 401 Unauthorized – Indicates that the client is not authorized to access the resource and should request again with the necessary login information.
  • 403 Forbidden – Indicates that the request is valid and the client is authenticated, but the client is not allowed to access the page or resources for any reason. For example. Sometimes authorized clients are not allowed to access the directory on the server.
  • 404 Not Found – Indicates that the requested resource is not currently available.
  • 410 Gone – Indicates that the requested resource is no longer available but was intentionally moved.

5xx (Server Error Category)

  • 500 Internal Server Error – Indicates that the request is valid, but the server is experiencing a problem and the server is required to serve an unexpected condition.
  • 503 Service Unavailable – Indicates that the server is unavailable or not ready to receive and process requests. Mostly if the server is under maintenance.

Field Name Casing Convention

You can follow any casing convention, but make sure it fits in the application. If the request body or response type is JSON then use camelCase to maintain consistency.

Searching, Sorting, Filtering, and Pagination

All of these actions are simply queries on a data set. There will be no new API set to handle these actions. We need to connect query parameters to the GET method API.

To understand how to perform these actions, come up with a few examples.

  • Sorting – In case the client wants to receive a list of sorted companies, GET /companies endpoint will accept many sort parameters in the query. For example. GET /companies?sort=rank_asc will sort companies in ascending order.
  • Filtering – To filter the data set, we can pass various options through query parameters. For example. GET /companies?category=banking&location=india will filter company listing data with bank company directory and location: India.
  • Searching – When searching for a company name in a company list, the API endpoint should be GET /companies?search=Digital Mckinsey .
  • Pagination – When the dataset is too large, we split the dataset into smaller sections, which helps improve performance and make it easier to handle responses. For example. GET /companies?page=23 means get a list of companies on page 23.

If adding multiple query parameters in the GET methods causes the URI to be too long, the server may respond with 414 URI Too long HTTP status code. In those cases, the params may also be passed into the request body of the POST method.

Versioning

As your APIs are being used by the world, upgrading APIs with some groundbreaking changes will also lead to disruption of existing products or services using your API.

http://api.yourservice.com/v1/companies/34/employees is a good example, with the API version number in the path. If there are any major groundbreaking updates, we can name the new API set v2 or v1.xx

Conclusion

These tutorials are based on my experience in development. I would love to hear your views on the issue mentioned above. Feel free to leave a comment, and let me know!

 

Article translated from:

https://medium.com/better-programming/restful-api-designing-guidelines-the-best-practices-39454135f61

Share the news now

Source : Viblo