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. 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.
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.
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.
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 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.
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.
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.
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.
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.
Previously published at https://dev.to/omegapointzero/5-best-practices-for-designing-restful-apis-331k