RESTful API Design Best Practices (Principles)

Dilanka Muthukumarana
7 min readJun 28, 2019

--

Modern day in software development, design and architectural discussions, the most common topic is this RESTful APIs which has more benefits compared to other concepts. With a few reads of the web articles, I thought to share my knowledge and experience of designing/developing RESTful API design.

Let's talk about the benefits of the REST over other concepts such as SOAP.

  • Simplicity to build and adapt.
  • Low resource usage.
  • Explicit processes or process instance.
  • The client does not need to manage routing information, only initial URI enough.
  • The client can depend on only a generic listener interface.
  • REST allows various data formats.
  • High-performance gain over SOAP. (faster and less bandwidth usage).
  • Comply with HTTP protocols.

And there are so many advantages and disadvantages as well over the monolithic application concepts.

Modern software designs are mostly tight with microservices and RESTful implementations. What is this? and why?

Note: REST — (Representational State Transfer)

source: https://shareurcodes.com

Microservices vs RESTful

Simply, Microservice architecture involves multiple applications which are developed separately without depending on any other applications and applications run/deploy independently or together. REST is an HTTP-based web service for communication between those applications.

Means that REST facilitates microservices to communicate among them. Since microservices is more about software architectural concept and a RESTful API is more on how to expose those microservices to the users with highly cohesive and loosely coupled.

So implementing RESTful API should have principles to follow which make the API more useful.

Assume that we have to implement the API for CRUD operations of the employee database. Let’s consider the most frequent scenarios.

  1. Fetch all employees.
  2. Fetch employee by id.
  3. Save employee
  4. Update employee
  5. Fetch employee by department
  6. Delete employee by id

Let’s have a look design fundamental of RESTful API.

  1. Simple API endpoints
/employees    
/employees/1234

2. Use Nouns instead of Verbs for URIs

what is correct?

/employees    
/employees/1234

what is wrong/inappropriate?

/getAllEmployees
/getEmployees/1234
  • Do not use long URI patterns with verbs( this is not mandatory, but best practice).
GET /getAllEmployees
GET /getEmployees/1234
POST /addEmployee

Note: But in some API design patterns using this, such as action based APIs. Those APIs are totally based on business actions. We will discuss them with a separate article “ An action based microservice architecture” in a later time.

3. User Parameters along with URL instead of operational URIs.

what is correct?

/employees?dept='HR'
/employee?id=1234&dept='HR'

what is wrong/inappropriate?

/getAllEmployeesInHRDepartment
/checkEmployeesInHRDepartment/1234

4. Use sub-resource for data relationships

Instead of parameterized URIs, you can use sub-resource URIs to manipulate or fetch the resources.

// below URI must return all employees belongs to HR department/departments/HR/employees

5. Use the appropriate HTTP method.

RESTful APIs have a number of methods to indicate the type of operation we are going to perform with this API. By performing an API call;

  • GET — Fetch a resource or collection of resources.
  • POST — To save/create a resource or collection of resources.
  • PUT/PATCH — To update the existing resource or collection of resources.
  • DELETE — To delete/remove the existing resource or the collection of resources.

Always need to know to use the correct and most appropriate HTTP method for a given operation.

GET /employees      // use plural nouns empoyees instead of employee
GET /employees/1234
POST /employee // send the data with POST object and return the created objectDELETE /employee/1234 // should delete resource from the data store or collection

6. Use proper HTTP error handling

Since all the REST API calls are HTTP if some error/exception thrown from the server side, it will give HTTP error to the invoked client. As a best practice, we must handle them in a proper way to identify it as a meaningful way without impacting to the current business flow.

As this HTTP codes are standardized codes which may return in various scenarios. We can assume that the server always returns the correct code to the client.

source: https://www.codetinkerer.com

According to the standards, we can categorize them to a few categories.

  1. Success (starting with numeric 2, 2xx)
  2. Redirection (starting with numeric 3, 3xx)
  3. Client Error (starting with numeric 4, 4xx)
  4. Server Error (starting with numeric 5, 5xx)

Most frequently used error codes in RESTful APIs

(Please note that this error codes and descriptions are copied from other resources as they are standard codes)

  • 200-Ok HTTP response for every success for GET, PUT or POST.
  • 201-Created HTTP response for success and resource had created and not response body or response body is empty.
  • 204 No Content HTTP response for the request is successfully accepted and send acknowledge to the client.
    DELETE request can be a good example for this.
DELETE /department/HR/employee/1234  or
DELETE /employee?dept='HR'&id=1234
  • 304 Not Modified indicates that the client has the response already in its cache. And hence there is no need to transfer the same data again.
  • 400 Bad Request HTTP response for the request by the client was not processed, as the server could not understand what the client is asking for.
  • 401 Unauthorized HTTP response for the client is not allowed to access resources and should re-request with the proper authentication or credentials.
  • 403 Forbidden HTTP response for the request is valid and the client is authenticated, but the client is not allowed access the page or resource for any other reason. E.g sometimes the authorized client is not allowed to access the directory on the server.
  • 404 Not Found HTTP response for the requested resource is not available to access.
  • 410 Gone HTTP response for the requested resource is no longer available to access or permanently moved.
  • 500 INTERNAL SERVER ERROR — HTTP response indicates that there might be a system failure.
  • 502 BAD GATEWAY — HTTP response indicates that the server received an invalid response from the upstream server/system.

Furthermore please see this resource for the detailed description of the HTTP error codes;

7. Versioning the APIs

This is one of the most important parts of the API design. Almost all the companies that provide software services, they are keen to upgrade or provide more useful functions to the users of the API. So that API will not be at the rest once it is released to use. But once API released, what happened the current functionality changed in the next day and API request and response not comply with the day as it is released. You and the user of the API will get impacted for the business.

So the best practice is to release the new version of the API with the improvements by keeping old API as it is.

/v1/employees
/v2/employees

Once all the integration is done or you can give a timeline to API users to get comply with the new API and inform them you are going to stop supporting or deprecate the old API after the timeline.

you can give major and patch version of the APIs as below;

/V2/employees  // Major version
/V2.x.x/employees // patch/minor or dev versions

8. Other useful operations (Filtering, pagination, Sorting)

As these operations are actions which will not support from the HTTP methods, you can achieve them using query parameters along with the URI.

such as:

// default sort will ne ASC. you only need mention you need descending order./emplyees?sort='dsc'// pagination can be achieved by limit params/employees?limit=10  // retrieve next 10 resource collection/employees?page=5    // you can have pagination logic in server side// Filtering can  be achieved by parameters
/employees?dept='HR'&dob='dd-mm-yy'

9. Decide support request/response formats

It is very important that how the API accepts the request with data and respond with data. According to your user’s or other 3rd party systems. Mostly REST APIs comply with the JSON. but some companies used with the XML as well.

10. Use proper/identifiable error messages.

As RESTful APIs are HTTP based method invocations. Respond error also based on the HTTP error codes. So that you have to handle errors in an appropriate manner. It is best practice to use keep standard error codes and messages mapping for your application related and use them along with the response.

Ex:

{
"error": {
"code": 1234,
"type": "ResourceNotFoundException",
"trace_id": "MYAPP_#ASWDXCDRT&SDSDE",
"message": "(#1234) Employee that you requested is not found",
"trace_log": " detailed exception if you need to send to the client side"

}
}

11. User standard specification

Finally, you may have different ideas, suggestions, approaches to define better API for your application. But it is better to use an industry standard approach to define and implement the API. So here is the world standard for the RESTful API design with the support of other authentication and authorization mechanisms that helps to your API to communicate with the rest of the world applications when needed.

Open API Specification: https://swagger.io/resources/open-api/

Thank you

Apart from the above mentioned best practices, you may have different suggestions and approaches to design RESTful API. Please feel free to respond to this article if any.

Finally, thank you for the read and if you think this is useful to update your knowledge or helps to your developments, please give some claps and do not forget to correct me if I am wrong.

Note: Please note that the content of the article is based on my experience and gained knowledge from the readings of web articles.

Stay with me as my next article plan is about architecting/scoping micro-services patterns.

More reads

--

--

Dilanka Muthukumarana
Dilanka Muthukumarana

Written by Dilanka Muthukumarana

TOGAF® Enterprise Architecture Practitioner | Consultant For Services: https://devinsights.tech/ Buy me a coffee: https://buy.stripe.com/8wMbMpdvO31ycsUbII

No responses yet