5 Best Practices for Designing RESTful APIs
Tags: heroku, node, api, rest
Published: 2020-04-13 22:19:51

RESTful APIs are everywhere, powering more of the modern world than any other API architecture. REST accounts for up to 80% of APIs [according to this study by ProgrammableWeb](https://www.programmableweb.com/news/which-api-types-and-architectural-styles-are-most-used/research/2017/11/26). How those APIs are built and structured can make or break a company in today’s ultra-competitive world. Poorly-designed APIs can be difficult to use, can fail when they are needed most, and are valuable targets for hackers looking for sensitive data. On the other hand, a well-designed API that utilizes best practices makes development a breeze, attracts new customers, and creates confidence among users that can boost retention rates.

# What is a RESTful API?

REST is an acronym for **RE**presentational **S**tate **T**ransfer, 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](https://devcenter.heroku.com/articles/mean-apps-restful-api) 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](https://en.wikipedia.org/wiki/List_of_HTTP_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:

![Use Status Codes!](https://dev-to-uploads.s3.amazonaws.com/i/wtzf8frzvao8r8g8whnh.png)

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 documentation](https://devcenter.heroku.com/articles/platform-api-reference#release) illustrates 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.

![Heroku's API documentation is clean, organized, and gives developers everything they need.](https://dev-to-uploads.s3.amazonaws.com/i/hw26itoahd66usehk54c.png)

Heroku's API documentation is clean, organized, and gives developers everything they need.



## 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](https://www.npmjs.com/package/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](https://restfulapi.net/security-essentials/) 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](https://helmetjs.github.io/). Implementing this middleware is easy:

![Hemlet.js](https://dev-to-uploads.s3.amazonaws.com/i/dnm15n9e5vv8pfw2onzv.png)

To prevent an API from leaking sensitive customer data, such as passwords, [write unit tests](https://www.testbytes.net/blog/api-security-testing-rules-and-checklist/) 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](https://nordicapis.com/what-data-formats-should-my-api-support/): 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.