Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 28, 2022 06:05 pm GMT

An Ideal REST API - Best Practices

What are APIs and why do we need them??

API stands for Application Programming Interface. It provides a standardized way for two applications (Client and server) to send and receive data. This is useful when you need scalability in your application.
For example:

Imagine you are building an eCommerce website. And you want your frontend (Client) and backend (Server) to be independent of each other, you can make use of APIs. Or you need a service like shipping/delivery and don't want to develop an entire shipping application just to fulfill a service of your eCommerce app. So, you decide to go for a shipping service provider who already has it working. The service provider will give you an API so that your eCommerce application can communicate with the service Provider's application.

What is REST API?

Well, Representational State Transfer (REST) is a guideline/architectural style for building APIs.

Here are some of the best REST API Practices that I follow

0. Using JSON to send and receive data

Unlike XML, JSON is much more readable and can be easily encoded or decoded. And also has a wide range of framework support.

Some widely used programming languages have inbuilt methods to parse/manipulate like

  • JavaScript has JSON.parse(), JSON.stringify(), etc...
  • PHP has json_encode() and json_decode().
  • Python has json.loads() and json.dumps().

1. Forming a Right URL/Endpoint

{{baseURL}}/{{area}}/{{version}}/{{collection}}/{{uniqueId}}

for example:

https://yourdomainname.com/api/v1/customers/123

you can also have the nested approach
for example:

https://yourdomainname.com/api/v1/customers/123/orders/1

The main objective of forming a right URL/Endpoint is readability. So, not to destroy the objective try not to nest more than two or three levels. But not more than that or else you will end up writing a solution which is a problem itself.

2. Plural Nouns Instead of Verbs in Endpoints

As you would be building a REST API which follows some strict rules to make use of the HTTP methods (CRUD methods)

  • GET: Used to retrieve entity(ies) and not to create or update.
  • POST: Used to create a new entity.
  • PUT: Used to update an entire entity.
  • PATCH: Used to update an entity partially.
  • DELETE: Used to remove/delete an entity

There are many more HTTP methods.

As you can see above that all the HTTP methods are verbs so there isn't any explicit need to add verbs to your endpoint.

for example:

You can have your endpoint like

https://yourdomainname.com/api/v1/customers

Instead of

https://yourdomainname.com/api/v1/createCustomers

Let the HTTP methods tell what the endpoint is doing.

wondering why plural??

  • In short, You won't be having a single resource in the database. You will be dealing with the multiple resources and it's better to let the other developers know.

3. Use of Error Codes

A REST API should always have an HTTP status code in its response. This will be helpful to handle the errors in the frontend as well and also makes the users aware of the request whether it is successful or something has gone wrong.

below are the example code ranges

Statusmeaning
100 199Informational Responses. Ex: 102 indicates the resource is being processed
300 399Redirects. Ex: 301 means Moved permanently
400 499Client-side errors Ex: 404 means resource not found
500 599Server-side errors Ex: 500 means an internal server error

4. Using a Consistent Response Structure.

It is important to maintain a consistent response structure for all the endpoints. An ideal response structure should include the following.

for successful response

  • status (boolean)
  • message (string)
  • data (response object)

for example:

{  "status": true,  "message": "Customer deatils fetched successfully",  "data": [    {      "id": 07,      "firstName": "Maroof",      "lastName": "L",      "age": 27    }  ]}

For error response

  • status (boolean)
  • errors (error object)
{  "status": false,  "data": [    {      "error": "error-001",      "message": "Incorrect username and password",      "detail": "Ensure that the username and password included in the request are correct"    }  ]}

5. Field Naming

we can follow some rules to make the responses readable. Here are some.

  • Field names should be camel casefor example: firstName, lastName, etc...
  • Field names should not contain hyphen, underscore or spaces.

6. API Versioning

REST APIs should have different versions. As mentioned above in forming a right URL structure, I had mentioned the API version.
Many famous applications do use the API versioning. You can checkout some applications like Facebook, YouTube, Spotify, etc...

API versioning is required when there is a major upgrade which can break the application for some users and the users would have an option to upgrade or not.

Last but not the least "in this blog"!

7. API Documentation

Responsibilities

So, now you have written a REST API which does incredible magic. Someone wants to make use of it. And to help them figure out how the API can be used, it must have good documentation.

The documentation should contain the following:

  • API endpoints with example payload/request body
  • example response
  • example error codes and error responses

Conclusion

It's important to put these best practices into practice to build reliable REST APIs.

There's always a scope for betterment. You can correct or add it in the comment box.

Thank you for reading. Happy coding.


Original Link: https://dev.to/imaroof07/an-ideal-rest-api-best-practices-4k89

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To