RESTful API Design Guidelines — Principles of Designing Better REST APIs with Examples

How to create an attractive REST API design for your application and why it is important to have a well designed REST API following some fundamental principles and guidelines. It is important for your application to have a well crafted and good designed API to attract client developers to use your web services instead of your competitors.

rest api design the complete guidelinesHi folks for another tutorial. Today, we will see how to create an attractive REST API design for your application and why it is important to have a well designed REST API following some fundamental principles and guidelines.

REST APIs

First of all let’s define what REST stands for. Representational State Transfer (REST) is the name given by Fielding to his description of the Web’s architectural style in his Ph.D. dissertation.

In today’s web architecture, web APIs are used heavily to allow and facilitate communication and exchange of data between web services and developer community programs. Generally speaking, a web API is the face of a web service that exposes program resources to the whole world by listening and responding to the client requests.

Modern web services adopt the REST architecture as a design to their APIs, which makes them RESTful. A Web API in compliance with the REST architectural style is by definition a REST API.

It is important for your application to have a well crafted and good designed API to attract client developers to use your web services instead of your competitors.

The API is an interface used by developers to interact with data. A well designed API is straightforward to use and simplify developer’s tasks. If the API is complicated to use, developers will start looking away for other alternatives, therefore, it is important to keep it simple. Developers’ experience is the most important metric to take into consideration while designing your API.

Google, Facebook, Amazon, Netflix and many more tech giants offer their services and data for developers to use and consume through APIs.

So let’s see how to design a good and clear RESTful APIs for your application following some straightforward principles and rules.

Terminologies

Below you will find the most used terms associated with REST API architecture.

Resource: is an object defining something in the real world using data, it can also have a set of methods to manage it.

E.g. Users, Cars, Schools and Students are resources and add, update, delete are methods that manages these resources.

Collections: is a group of resources, e.g. Departments is the collection of Department resource.

URL: is the path used to access a resource and apply some actions on it.

API Path Format

Add a subdomain named api.

Your API’s full domain name needs to have a subdomain named api to distinguish between different application services. For example:

http://api.weather.com

Add a Developer portal subdomain.

If your API will be accessed by client developers, you should add a developer portal subdomain named developer which will have the documentation about your API and how to access it. For instance:

http://developer.weather.com

Use nouns instead of verbs.

Let’s see an example of Departments which contains some Teachers, to clarify more. The following are some APIs related to a Department resource.

/departments/getAllTeachers

/departments/addNewTeacher

/departments/deleteTeacher

/departments/deleteAllTeachers

If you see this example you will notice that we will have to write plenty of API endpoints for different operations, which will be very complicated to maintain as the API count increases.

What is wrong with this? It is more convenient that the API only contain resources name (nouns) not verbs or actions. The API /departments/deleteTeacher has the delete action with the resource name Teacher.

So, what is the right way to do it? Use only the resource name like /departments endpoint, which has no actions. But how to distinguish between the actions we want to perform on the resource whether it’s an Add, delete or update action?

The HTTP Methods (GET, POST, PUT, DELETE) called verbs is the answer for this question.

Use plural nouns for resources and path variables to identify a unique resource.

It is always a good practice to use plural noun for resource name in API endpoint and if we need to get only one instance of the requested resource, we have the possibility to pass the id as a path variable to identify the unique instance. For example:

Method GET: http://api.football.com/teams should return the list of all teams.

Method GET: http://api.football.com/teams/{team _id} shows that we can tell the backend this is a path variable segment using curly brackets. If team_id equals 10, the resulted path would be: http://api.football.com/teams/10 which should return the team with id 10.

There are also some other use cases where we have a resource composed of resources, e.g. Team is composed of Players resource. An example of API endpoints would be:

Method GET: http://api.football.com/teams/2/players will return a list of all players which play for team 2.

Method GET: http://api.football.com/teams/2/players/11 will get the details of player 11 from team 2.

Method POST: http://api.football.com/teams/2/players will add a new player to the team number 2.

Did you notice now how the APIs are more concise and consistent? 😎

Use Query Strings

If you want to filter, sort, research or paginate a collection of resources without the need to create new APIs, you have to use additional parameters as query params with the GET method API like the following examples.

Searching In case, the client wants to search for a player name in the player’s collection, the API path should be GET /players?search=Lionel Messi

Filtering the dataset based on various parameters we can use:

http://api.football.com/teams/10/players?position=defense better than:

http://api.football.com/teams/10/getPlayersByPosition

Pagination split the dataset in smaller chunks when we have a large number of entries, which improves the performance.

http://api.football.com/teams?pageSize=20&pageIndex=5 better than:

http://api.football.com/getTeamsByPageAndSize

Sorting you should provide this feature to the clients of you API and allow them to sort the data based on various parameters, if the client wants to get a sorted list of players, the GET /players endpoints should accept multiple sort params in the query. For example:

http://api.football.com/teams/10/players?sort=name_asc would sort players collection by ascending name order.

The API paths must use the plural form for the resource name and the HTTP methods must be used to indicate what type of action is performed on the resource.

HTTP Methods (verbs)

HTTP has a set of methods which specify the kind of action to be applied on the resources.

GET method returns a response body containing a representation of a resource. GET requests can be repeated without producing side effects.

e.g. GET /teams/5/players gives all the players from the team 5.

HEAD method is used to get headers without a body and to check whether a resource exists or not.

e.g. HEAD /teams/5/players/1 will return headers about the player 1 resource.

PUT method must be applied to update a mutable resource or create a new if it doesn’t exist. The PUT method is idempotent, in other words multiple requests will have the same result.

e.g. PUT /teams/5/players/10 will update the player 10 with data provided in the request body or create a new one if it doesn’t exist.

POST method requests the server to create a new resource in an existing collection when a form is submitted. Repeated POST requests may cause undesirable side-effects this is why it is considered as non-idempotent.

e.g. POST /teams/5/players will create a new player of team 5.

DELETE method will ask the server to remove resources or its instance completely from the database. Once the DELETE method is performed the user cannot find the resource anymore and any future GET or HEAD request to that resource will result in a 404 “Not Found” status code returned by the API.

e.g. DELETE /teams/5/players/19 will delete the player 19 from the players collection under team 5.

HTTP Response Status Codes

When the user performs an API request to get some data, the user needs to know the server’s response, in other words, if it failed, accepted or the request was incorrect. HTTP defines categories of standard status codes that can be used to communicate the response returned by the server. The server should use the correct status code when responding to the client’s request.

Below you will find the main categories of HTTP Status Codes.

2xx (Success)

These status codes indicate the client’s request was received and accepted successfully by the server.

200 “OK” shows that the REST API responded successfully to the action requested by the client. A 200 status code response has to return a response body in contrast to 204 status code.

201 “Created” must be returned whenever a resource is created successfully. For example using POST method to create a new resource should always return the 201 status code.

202 “Accepted” indicates that the client’s request was valid but needs time to be processed and it will be handled asynchronously.

204 “No Content” shows that the client’s request is processed successfully but the API didn’t send any response body. The DELETE action is a good use case of this, when we ask the API to delete a resource, we don’t expect to get data in the response body. If the resource to be deleted does not exist, the response status code returned must be in the 4xx Client Error category.

3xx (Redirection)

304 “Not Modified” is used to preserve bandwidth by indicating that the user already has the most recent response in its cache, therefore it is not required to send the same response again.

4xx (Client Error)

400 “Bad Request” indicates that the server cannot understand what the client was looking for and hence the request got rejected by the server.

401 “Unauthorized” shows that there is an issue with the client’s credentials and it is not allowed to access this resource until he provides the proper credentials.

403 “Forbidden” indicates that the request is correct and the client is authenticated, but the client doesn’t have the permission to manipulate this kind of resources. For example the admin has high level permissions unlike a normal user.

404 “Not Found” indicates that the REST API cannot find the requested resource currently.

405 “Method Not Allowed” indicates that the HTTP method used is not allowed by the resource.

410 “Gone” shows that the resource is no longer available and it has been moved deliberately.

415 “Unsupported Media Type” indicates that the media type supplied by the client’s request cannot be processed by the API

5xx (Server Error)

500 “Internal Server Error” it is a generic REST API error response which indicates that the request is correct, but the server encountered some unexpected problems when processing the request like triggering an exception.

503 “Service Unavailable” shows that the server is under maintenance and cannot process future requests currently.

Supported Media Types

When designing your API, you must decide which form of the data will be accepted by the backend and the form of the data returned to the client. The Content-Type header’s value specifies the Media Type supported. For the modern applications, the JSON format should be used for requests and responses. But, if you have a legacy application, you may need to use XML as well.

Versioning

It is always a good practice to include the version number of the API in the path, so any APIs upgrade with some breaking changes will be visible to the consumers of your API by incrementing the version number.

For example http://api.football.com/v1/teams/29/players defines the version number of the API. When we have a breaking update, we should modify the version number of the APIs to v2.

This compilation of guidelines is the fruits of my research and my experience as a web programmer.

RESTful API design guidelines best practices

If this article helped you in any way, then you can buy me a coffee 😉

#API #Design #SoftwareDevelopment #Programming #RestfulApi #BestPractices

Name

Angular,7,Angular 8,1,Best Practices,1,Design,1,Firebase,1,Ionic,1,Java,5,Nodejs,2,Python,1,Restful API,1,Software Development,1,Spring,3,Spring Batch,1,Spring Boot 2,1,Web Development,1,
ltr
item
Programming Tutorials, News and Reviews: RESTful API Design Guidelines — Principles of Designing Better REST APIs with Examples
RESTful API Design Guidelines — Principles of Designing Better REST APIs with Examples
How to create an attractive REST API design for your application and why it is important to have a well designed REST API following some fundamental principles and guidelines. It is important for your application to have a well crafted and good designed API to attract client developers to use your web services instead of your competitors.
https://4.bp.blogspot.com/-KFkxXEpyKpU/XTISqC6FnnI/AAAAAAAAATo/XaktrqHz-XEIRE1tnfKy_TMyUkJOQVqqACLcBGAs/s200/detailed-rest-api-design-complete-guidelines.jpg
https://4.bp.blogspot.com/-KFkxXEpyKpU/XTISqC6FnnI/AAAAAAAAATo/XaktrqHz-XEIRE1tnfKy_TMyUkJOQVqqACLcBGAs/s72-c/detailed-rest-api-design-complete-guidelines.jpg
Programming Tutorials, News and Reviews
https://www.ninjadevcorner.com/2019/07/restful-api-design-guidelines-principles-of-designing-better-rest-apis-with-examples.html
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/
https://www.ninjadevcorner.com/2019/07/restful-api-design-guidelines-principles-of-designing-better-rest-apis-with-examples.html
true
493653397416713395
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy