Skip to main content

Best Practices for Designing RESTful APIs

What is a RESTful API?

REST is an acronym for REpresentational State Transfer, and describes an architectural style for creating distributed web services. REST allows users to use standard HTTP requests to remotely call code and receive responses. REST has several advantages over other protocols:
It separates data storage concerns from the user interface, meaning a back-end server running an API can handle all of the logic to access databases and manipulate data before returning it to a user in a uniform, structured way. This consistent access and structure of data allows developers to build front-end applications easily, which makes porting the front end of your app to other platforms a breeze.REST APIs support caching of commonly requested static resources, lending to better performance.REST is stateless, so all information to complete the request is included in the request. This simplifies the API by removing the need for server-side state synchronization logic. This also makes scaling easier, as any server can handle any request without tracking sessions.
(If building RESTful APIs is new to you, or you want a sandbox to try out these best practices, try out this reference architecture from Heroku that is quick and easy to deploy.)
So now, here are the top five best practices for building your RESTful APIs.

1. Use Error Status Codes

HTTP has over 100 status codes already built in. Using status codes in your RESTful API to communicate the general error is a godsend for developers. Developers will be able to immediately identify the issue, which means spending less time writing parsers to handle all the different types of errors. Is the request being denied because the session is not logged in? There’s a status code for that.
Is there a missing resource? Did the CRUD service receive the request but fail to connect to the database? There are status codes for those, and nearly every other common behavior. Status codes can also be combined with specific error messages to provide detailed information about unsuccessful requests.
Here’s a snippet of code from a Node.js API to illustrate:
This endpoint returns a user profile by the passed-in user ID. The status codes sent in response to the requests tell developers exactly what error happened, making the response easier to handle and saving them significant time and trouble.
Developers can implement routines for handling different errors based on status codes, while the API provides detailed error information. In this case, the 404 error tells the caller that something can’t be found. The JSON in the response tells the caller specifically that it’s the user ID that can’t be found, rather then being ambiguous about whether the error refers to the endpoint or requested resource.

2. Good Documentation

Documentation is one of the most important — and most overlooked — aspects of an API. Official documentation can be a customer’s first point of contact with a product, and a key factor in whether or not a development team adopts it. Good documentation looks clean and consistent, and adequately prepares a developer to use your API quickly.
The faster someone can learn your API, the faster they can start producing with it. Documentation should have a uniform look, and include all of the relevant information: the endpoint, compatible methods (GET, POST, PUT, etc.), what parameters are optional and required, and the data type expected.
This screenshot from Heroku’s platform API documentationillustrates what complete documentation for developers looks like. It shows the action taken, the endpoint accessed, and the HTTP method used. It also supplies detailed information about the optional parameters and shows the user a working example of everything implemented correctly. The sample responses also illustrate how the returned data will be structured.

3. Rate Limiting and Throttling

API requests can be resource intensive, requiring serious computing power and storage. If you aren’t careful, a large number of successive, concurrent requests can slow down or even DOS your server.An easy way to do this is to use one of the many available tools like express-rate-limit, an Express middleware designed specifically to handle Rate Limiting in an easy, intuitive way.
You can also implement rate limiting logic tied to authentication, allowing greater flexibility in controlling permissions granted to each user. By requiring users to authenticate, it’s possible to track the number of requests each users sends, which also allows you to limit or stop those requests. Different users can also be granted access to different API endpoints. For example, a user who is an Administrator could access more information, or more requests, from an API than a regular, unprivileged user. Another benefit of using authentication is the security it provides, bringing us to our next best practice.

4. Secure The API

APIs need to be secure! Hackers use automated scripts to attack services indiscriminately, so an API needs to have proactive security measures to keep operations running smoothly and to protect sensitive data. First and foremost, every web application should have a HTTP Strict Transport Security (HSTS) policy to ensure all connections are encrypted. Securing the connection prevents network sniffing, man-in-the-middle attacks, protocol downgrade attacks, and session hijacking via cookie theft.
You may also want to set and hide certain headers that can be exploited, such as those that reveal information about your API infrastructure that may be useful to attackers. There are many tools out there that can handle this. For instance, if you’re running an API with Node.js, you can use something like Helmet.js. Implementing this middleware is easy:
To prevent an API from leaking sensitive customer data, such as passwords, write unit tests for security testing. Last but not least, you should require an authentication token to access your API. This allows developers to control who has access to what information. It can also make it easier to stop attacks on the API server by denying offending users.

5. Use JSON

The purpose of an API is to serve data from your company’s resources. There are three formats that are commonly used to return the data according to Nordic APIs: XML, YAML, and JSON.
XML is easily human-readable, but the data is contained within a set of markup tags, which quickly grows in size and requires extra bandwidth. Developers also have to parse the contents of the tags to access the data.YAML, by contrast, uses very little bandwidth, but requires either an external library or a custom parser and encoder to work with the data.JSON beautifully marries the worlds of XML and YAML together: it’s human-readable without needing high bandwidth or custom parsing to move the data into a JavaScript-compatible structure.

Conclusion

Implementing these five practices with your RESTful APIs will make your API easier and safer to use. A safe, secure API with good documentation can deliver a great developer experience, and the added ease of use will help your adoption rates. Furthermore, these best practices will keep your code clean, and your operations running smoothly, and your customers happy.

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...