6 Strategies for Releasing Efficient REST APIs

A hands-on look at some key strategies for releasing effective and efficient REST API implementations

Geertjan Wielenga
Apr 6th, 2022
Share

Representational state transfer (REST) APIs, also known simply as APIs or web APIs, help accelerate integration between enterprises and enable the developer community to access products. Built atop the HTTP protocol to support developing custom solutions, RESTful APIs have experienced tremendous popularity since the early 2000s, although some developers prefer other API development approaches, like GraphQL.

Virtually every SDK and framework offers a native HTTP library, enabling organizations to develop solutions as APIs. As one might imagine, ensuring a consistent ecosystem for APIs has become crucial. It requires adherence to industry best practices for API design and development.

API customers can be developers or organizations. Therefore, you should ensure the best possible first impression of the API. You can improve documentation, the data interchange format, security, API versioning, and the use of the HTTP protocol. These areas are straightforward to tackle and will provide a significantly more enjoyable experience for your customers. Moreover, you can apply these practices to every framework and runtime.

Below, we’ll share some best practices for API design and development. The sample code contains JavaScript and Node.js for the RESTful API. Some references such as db are hypothetical. If you are looking for support on building a RESTful API, check out our guide and then circle back.

Creating documentation

Your customers use the documentation on your website or an SDK to understand your APIs. You can create the documentation for a RESTful API in various ways. A few such documentation methods are:

  • Swagger or the OpenAPI specification
  • API references, such as generating documentation using Javadoc
  • Design-first APIs, such as those driven by design and using business requirements to develop the API
  • Collections-based documentation, such as that made with Postman
  • README files generated in open-source projects

Paid plans often provide integration or value-added services on top of your existing API. For example, documentation services often allow customers to use the API right from the browser.

When customers visit your RESTful API page, they read about your RESTful API’s flows, how to use the API, and the services it provides. Updated documentation provides a positive user experience and can help with your RESTful API conversion rates. Users are more likely to choose clear and transparent APIs for their solutions.

You can run a job during the software build to build your documentation. The documentation job can pull your project’s comments and other resource types. This way, every version of your API has documentation that updates with software changes. You can version the documentation using your software build’s version.

If you use Swagger to document your API, your code can use the comments to highlight the OpenAPI information, like this:

/**
 * @openapi
 * /books:
 * get:
 * description: Get all the books in the system!
 * responses:
 * 200:
 * description: Returns the list of all the books in the system.
 */
app.get('/books', (req, res) => {
 res.send(db.getBooks());
});

Above is an Express handler for an HTTP GET /books request with a description and response codes. The following sections of this article highlight applying, sorting, and filtering status codes.

One more exciting thing to note is that many developers prefer RESTful APIs. So, if you keep your APIs well-documented, you have much greater odds of success.

Handling data interchange

RESTful APIs use HTTP headers to prepare and handle data interchange. The Content-Type HTTP header asks clients and servers to negotiate the content they will interchange. Clients use the Accept header to express receivable content types. Servers can set the value for the Content-Type header according to the record it is transferring.

The most notable data interchange format in RESTful APIs is JSON notation. The benefit of using JSON is that it transfers a smaller amount of data over the network. JSON does not provide advanced features that XML provides, such as schema notation, but it is a mappable structure.

Various languages offer native support for JSON data. The JSON type in JavaScript offers a parse method that natively processes the JSON string and materializes the runtime object.

Communicating with HTTP verbs and status

Your clients connect with API servers to take specific actions. RESTful APIs offer a streamlined way to run certain operations.

An API’s URLs or endpoints should explain the steps to serve the request. The HTTP protocol uses certain verbs and status codes to communicate success and failure. The most used HTTP verbs are GET, POST, PUT, and DELETE. If you are familiar with create, read, update, and delete (CRUD) operations, you can recognize that these request verbs correlate to CRUD operations.

Using these verbs, you can do the following:

  • Use the GET request to read the data.
  • Create a new object using the POST request. A POST request creates a new resource and returns the object’s location to create an endpoint.
  • Use the PUT request to update an existing resource. This verb is idempotent, so the resulting state of the data store should be the same regardless of the number of requests.
  • As the name suggests, the DELETE verb deletes the resource from the system.

You can find other HTTP request verbs to help you extend the HTTP protocol in the official MDN documentation.

If you highlight and use these verbs with the request endpoints, customers can easily understand each request’s purpose. Therefore, instead of using /getBook and createBook, you can create a single endpoint, /books, and use GET and POST requests to differentiate operations.

Similarly, you can return the HTTP status codes to highlight success or failure. Code 200 indicates success, and other codes indicate a problem.

// We assume that we have a database helper to query and create the books.
app.get(“/books”, (req, res) => {
 	res.status(200).send(db.getBooks());
});

app.post(“/books”), (req, res) => {
 const { title, author, isbn } = res.body;

 // create the book resource
 // for example, const result = db.createBook({ title, author, isbn })
 if (result.success) {
 res.status(200).send(result.resource);
 } else {
 res.status(401).send(‘Cannot create the book resource.’);
 }
});

Note: The operations mentioned in this section are debatable. For example, some organizations discourage using PUT requests, instead preferring PATCH requests to modify specific fields.

Similarly, endpoint names should be plural and should not contain the verb in the endpoint. Use HTTP verbs to differentiate between the operations.

Often, these decisions depend on the culture and the software you are building.

Enabling data transformation

Once your API has documentation and HTTP verbs, the next step is to transform the data before sending it to the customers. The first reason to transform the data is to prevent the customers from receiving the entire database dump.

APIs use pagination to chunk the data into smaller pieces. You can allow customers to either use hardcoded page numbers or provide a limit and offset to query the data.

Additionally, you can pass the endpoint and query string variables to the backend services that query the data. Several object-relational mapping (ORM) techniques, such as Sequelize for Node.js, provide query LIMIT and OFFSET fields.

Customers can query the data from the beginning of the product’s lifespan or only the most recent data. You can configure this either by providing a field in the endpoint or by using the query strings to sort the data. Swagger and OpenAPI can document these filters for your customers.

By limiting the response size, you can minimize bandwidth consumption and increase the response throughput. If your API is a paid service, this would also prevent your customers from downloading the entire database in a few requests and potentially discontinuing their use of your solution.

Second, sorting data is an expensive operation. Your database can do that quickly with indexed information. If you send the query with data filter and sort operations, the response will return the correct data and sort order within a few milliseconds.

Versioning the API

Most APIs do not require a version. The customer always gets the latest version. However, if you have an SLA prohibiting API changes, you can use versioning. Versioning allows your developers to provide a stable service to existing customers and add new features.

The best way to version an API is using a version path in the endpoint, such as /v1/books and /v2/books. The two APIs can offer different features and capabilities to your customers.

Ensuring security and authentication

You should always run RESTful APIs behind an SSL layer, under an HTTPS endpoint. This approach builds trust with your customers and other developers. Use the automated Let’s Encrypt certificates or purchase an enterprise service as required by regulations or compliance requirements.

Unless your API is free for public use, consider using Bearer tokens to audit the API’s use. The tokens help ensure a reasonable API use policy.

Conclusion

You can take various steps to ensure your RESTful APIs are efficient and effective. For example, it’s important to provide high-quality API documentation since customers are more likely to trust a well-documented API.

Also, it’s best to use standard HTTP statuses and verbs to communicate errors, receipts, and other information. Additionally, receiving and replying with JSON promotes data interchange.

Furthermore, data transformation techniques like pagination and filtering help limit the amounts of data retrieved and minimize stress on the API. Lastly, versioning APIs helps ensure clients get new features, while security and authentication help keep the API and its users safe.

The domain of RESTful APIs is vast, and there are many important practices to follow for a stable and good-quality API. Although the practices mentioned in this article are not exhaustive, they aim to help you build a better API ecosystem.

Share