This blog highlights REST Best Practices intended for the developers who are interested in creating RESTful web services that provide high reliability and consistency across multiple service suites. We all know there are various resources on best practices for creating RESTful web services.
However, it should also be known that many of the available resources are conflicting. Also, it’s likely not doable to refer, read, and comprehend several books on this subject with a motto of implementing services “tomorrow”. This blog will enable you to quickly understand and grasp RESTful concepts with a major concern on best practices and conventions.
REST is an abbreviation of Representational State Transfer. REST represents the architectural style of the World Wide Web (WWW). REST is an approach to communication that makes simple HTTP calls for inter-machine communication. REST is often preferred over SOAP because REST does not use as much bandwidth as heavyweight SOAP does which makes it a better option for use over the Internet.
In REST, the calls will be message based and dependent on HTTP standards to describe these messages. REST can be understood as a simple request/response mechanism, where each request returns a response. The following fig. will give you a better idea:
RESTful API’s, more popularly termed as REST API’s are the web services written using REST architecture
REST is resource-based. When we talk about REST, it indicates things or resources as opposed to actions in SOAP. In RESTful services noun represents the resources, for example, a person resource, a useful resource.
We use an HTTP verb (POST, PUT, GET, DELETE, etc.) to indicate what operation the REST API has to perform. Resources are identified by URIs. It is possible to have multiple URIs pointing to the same resource. RESTful API’s generally accept/return data in json or xml format.
Let’s quickly form an example with this basic knowledge before moving further. Suppose Sagar is a resource, there is a service to fetch contact information using the HTTP verb GET which will return the data like name, address, phone number, email address in JSON or XML form.
Let’s have a small review of each:
It defines the interface between clients and servers. Uniform Interface simplifies and decouples the architecture. It enables each part to develop or evolve independently. Uniform interface describes the following four guidelines or principles:
It is not required for the webserver to remember the client’s state. The necessary state required to handle the request is included in the request itself, whether as part of URI, query-string parameters, body, or headers.
Clients can cache responses. Therefore Responses must explicitly or implicitly define themselves as cacheable or not which prevent the clients from reusing stale, old or inappropriate data in response to further requests.
The uniform interface is responsible to separate the clients from the servers. Servers and clients can be developed independently. It conveys that the clients are not concerned with data storage which is internal to each server, which increases the portability of the client code. Servers are not concerned with the UI or user state, which makes the servers more scalable and simpler.
A client is unable to tell if it is connected directly to the end server or to an intermediary server. Intermediary servers may improve system scalability by providing shared caches and enabling load-balancing. Security policies can also be enforced through layers.
It is possible for the servers to extend or customize the functionality of a client on a temporary basis by transferring logic to it that it can execute, for example, Java applets and client-side scripts like JavaScript.
Clients specify their desired interaction method in the Request-Line part of an HTTTP request message. Each HTTP method is bound to some specific, well-defined rules and meaning within the context of a REST API’s resource model.
The primary or most commonly used HTTP verbs or more properly called methods are GET, PUT, POST, and DELETE. These correspond to create, read, update, and delete operations respectively. OPTIONS and HEAD are the other verbs but are less frequently used.
The GET method is used to read or retrieve a representation of a resource. As the GET method (along with HEAD) is used for reading only purposes hence they are considered safe as they do not change the data. GET (and HEAD) are considered as idempotent, i.e., making multiple identical requests end up having the same result as a single request.
GET http://www.myexample.com/users/orders
GET http://www.myexample.com/users/12345
GET http://www.myexample.com/users
We use the PUT method mostly for update functionalities. Use this method for PUT-ing or updating data to a known resource URI along with the request body which contains the newly-updated representation of the original resource that we intend to change.
PUT method can also be used to create a resource in cases where resource ID is provided by the client instead of the server. But we must generally use POST to create new resources where the client-defined ID is included in the body representation.
PUT is not a safe method, although it is idempotent.
PUT http://www.myexample.com/users/123
PUT http://www.myexample.com/users/orders/123
POST method is utilized to create new resources. This method is not safe nor idempotent.
Examples:
POST http://www.myexample/com/users
POST http://www.myexample.com/users/orders/123
As the verb suggests, it is used to delete a resource identified by the URI.
DELETE http://www.myexample.com/users/123
DELETE http://www.myexample.com/users/123/orders
Forty standard codes have been defined by HTTP to convey the results of a client’s request. These codes can be divided into the following five categories:
CATEGORY | DESCRIPTION |
---|---|
1xx Informational | Indicates transfer protocol-level information. |
2xx Success | Indicates that the client’s request was accepted/processed successfully. |
3xx Redirection | Informs that the client needs to take some additional action to complete their request. |
4xx Client Error | This category of error status codes defines the client’s error. |
5xx Server Error | These error status codes indicate the server side errors. |
All Items | Description |
Let’s have a short and precise look over the success and error status codes.
CODE | NAME | MEANING |
---|---|---|
200 | OK | Indicates a nonspecific success |
201 | Created | Indicates that a new resource has been created |
202 | Accepted | Indicates the start of an asynchronous action |
204 | No Content | Indicates that the body was left blank |
301 | Moved Permanently | Indicates that a new permanent URI has been assigned to the client’s requested resource. |
303 | See Other | Sent by controllers to return results that it considers optional |
304 | Not Modified | Sent to preserve bandwidth (with conditional GET) |
307 | Temporary Redirect | Indicates that a temporary URI has been assigned to client’s requested resource. |
CODE | NAME | MEANING |
---|---|---|
400 | Bad Request | Indicates a non-specific client error. |
401 | Unauthorized | Indicates either client provided wrong/invalid credentials or missed to send them. |
402 | Forbidden | Indicates denied access to a protected resource. |
404 | Not Found | Sent when the client tried interacting with a URI which the REST API could not map to a resource. |
405 | Method Not Allowed | Sent when the client tried to communicate via an unsupported HTTP method. |
406 | Not Acceptable | Sent when the client tried to request data in an unsupportive type format. |
409 | Conflict | Indicates that the client attempted to violate resource state. |
412 | Precondition Failed | Informs the client that one of its pre-condition was not met. |
415 | Unsupported Media Type | Sent when the client submitted data which is of unsupported media type format. |
500 | Internal Sever Error | Tells the client that API is having problems of its own. |
Nouns are good and verbs are bad when it comes to rest standards. You can use the following easily understandable structure for every resource:
RESOURCE | GET (READ) | POST (CREATE) | PUT (UPDATE) | DELETE |
---|---|---|---|---|
/customers | Returns a list of customers | Create a new customer | Bulk update customers | Delete all customers |
/customers/1234 | /customers/1234 | (405 – Method not allowed) | Updates a specific customer | Delete a specific customer |
/getAllCustomers
/createNewCustomer
/deleteCustomers
Nouns are good and verbs are bad when it comes to rest standards. You can use the following easily understandable structure for every resource:
Never use GET to alter or state changes. Use GET, POST or DELETE to alter the state.
Keep the resource naming simple by following plural forms of nouns. Even though you might think that it is grammatically incorrect, but the best standard for REST practices is to use plurals.
/customers instead of /customer
/customers/12345 instead of /customer/12345
If you have some resource which is related to another resource then it is implied to use sub-resources:
GET /customers/1/products: Returns a list of products purchased by customer 1
The client-side and server-side both should know and use the format that is being used for communication. This format has to be specified in the HTTP-header.
Accept: It defines a list of acceptable response formats.
Content-Type: It defines the request format.
It is very difficult to work under situations where proper error handling is ignored. Just returning of HTTP 500 with a stacktrace log is not enough.. We need to make proper usage of the HTTP status codes that have been covered in the earlier part.
Pagination:
Use limit and offset for pagination. It is not only flexible for the user but also common in the leading databases.
Sorting:
Ascending and descending sorting should be provided. Also allow sorting over multiple fields.
Filtering:
We can make use of unique query parameter for all fields or may be use a query language for filtering purpose.
It is a very common practice that mobile clients wish to display only a few attributes. They don’t want to display or use all the attributes of a resource. Thus an API should have the ability that allow the mobile clients to choose the returned fields. This helps to save the mobile battery, reduce network traffic, and speeds up the API usage.
I hope the above content is easily understandable and lets you get started with developing REST API with some good level standards and consistency in your coding style. Just follow these REST best practices and you’re all set.
One last suggestion is to maintain an updated API document. This document should be shared and accessible to all concerned people. Most client-side developers should check the API document before starting the integration of web services. The doc should cover all necessary information like request URL, response body format, headers, etc. For every API try to cover with an example of request body and response bodies with all the alternative responses including error and success.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowEnhance Your Epic EHR Expertise in Just 60 Minutes!
Register HereMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork