7 Tips for Building an API

1717 VIEWS

·

As of 2018, businesses are relying more and more on APIs to serve their clients. Microservices and serverless architectures are becoming increasingly prevalent, and that creates a higher number of required API integration points to ensure a competitive advantage and business visibility.

APIs should be designed from the ground up with these needs in mind. In this article, I discuss seven design tips for APIs that can help to meet these goals. (I should note that these insights are based on my experience building APIs for mobile clients, but the lessons apply more broadly to include API design of any type.)

1. Treat your API as a Product

A key factor when starting with any sort of development is the notion of the product. It defines the stand-alone entity that exposes useful functionality and benefits to the market. It is no easy task to design and implement an API that is easily consumable, scalable, properly documented and secured without having a strong sense of responsibility and ownership in the process.

Thus, it’s only fair that your API is treated like one, complete with its own board, backlog and sprint plan. In addition, a Product Owner needs to be assigned to convey the vision of the ideal API to the agile team. Developers and testers must devise a plan to work with API best practices and also avoid common mistakes. The end product needs to be production-ready from day one.

2. Use an API Specification Framework

API frameworks are an attempt to standardize development processes across industries. Typically, they consist of an arsenal of tools that cover the whole development lifecycle, from concept to production. While it’s true that adhering to a specification like OpenAPI/Swagger while developing an API is more opinionated, it provides better tooling interoperability. Everyone loves automation, and having the ability to generate documentation, SDKs, and UI interaction points every time the code changes is very useful. If you care about standards and want to provide conventional tools when describing your APIs, then this is a very solid option that pays back in advance.

3. Use a Versioning Strategy

Your API is your product and it evolves over time as business requirements change. As a product, it has a specific version, so clients expect the right responses. Changing a published and used API interface is a ticking bomb. The last thing you want is to introduce breaking changes without clients knowing about it. This is especially true for mobile applications when users may still have old versions installed on their phones.

There are multiple ways to enforce versioning information upon your APIs. Most API designers opt for putting the version information in the URL, as it is practical. For example, the following URL represents a customer’s resource endpoint:

/api/v1/customers

It is very important to stick to a version strategy that is suitable for the business and the available tooling. Later on, if you decide to change a version, it will be easier to provide warnings, updates and other mechanisms.

4. Use Filtering and Pagination

One common mistake when developing an API is not offering a way to filter or paginate results. When you expose an API that returns a list of items that can change over time, you need to establish a pagination strategy. The reason is simple. Clients, especially mobile ones, cannot view hundreds of list items at once, so you can show the first 10 (for example). If your API returns the whole database listing for each request, then a lot of resources are being wasted and the performance degrades substantially.

Modern frameworks offer a way to paginate results, but you can also customize your own. A common approach is to use LIMIT and OFFSET statements on your queries. For example, see this MySQL statement for returning a slice of the total result:

SELECT * from customers LIMIT 5,10

This statement will retrieve rows 6-16 from the database so you can provide a JSON response that gives links to the first, next, previous and last page of that query based on the LIMIT parameters:

// _links
{
  “first”: “/api/v1/customers?page=1”,
  “prev”: “/api/v1/customers?page=1”,
  “next”: “/api/v1/customers?page=3”,
  “last”: “/api/v1/customers?page=9”
}

5. Use REST and HATEOAS

REST is a proven and battle-tested architectural approach to designing Web services, and it is independent of any underlying protocol. Thus, it is very suitable for designing APIs. By using REST principles, you can apply some design considerations, such as:

    1. Treating endpoints as resources that have a conventional naming scheme. For example, if you want to expose a list of orders, you expose the following endpoint:
GET /api/v1/orders
    1. If you want to find a specific order, you’ll supply an ID parameter:
GET /api/v1/orders/1
  1. This has several advantages, such as better uniformity, readability and consistency.

– Promoting stateless transactions. These help make the services more scalable as they won’t have the hard coupling constraints of keeping state between client and server communications.

– Easier navigation within the entire set of resources without prior knowledge of the internal URI scheme with the help of HATEOAS. It enhances the response model of each resource by providing a set of relevant links so that it is easier to interact with the API without looking up a specification or other metadata service. One good format of HATEOAS is the HAL specification. For example, here is a HAL response to a specific article resource exposing the relevant links for the reporters:

{
  “_links”: {
    “Self”: {
        “href”: “/api/v1/articles/1”
    },
    “/rels/reporters”: [
      {
        “href”: “/api/v1/reporters/1121”
        “fullName”: “John Doe”
      },
      {
        “href”: “/api/v1/reporters/192”
        “fullName”: “Alice Jansen”
      }
    ]
  }
}

6. Secure your Endpoints

You should not neglect security. Any breach can have catastrophic consequences and can lead to serious legal issues. Security controls need to be established early in the development process, and ideally, your API needs to be assessed by an external vendor. The CIA triad of security applies with the following:

  1. LConfidentiality is achieved by adding proper authentication controls that provide a means for your system to know who is accessing information or sites. OAuth2 and JWT offer a practical and secure means of providing this. HTTPS must be used at all public endpoints to ensure secure communications.
  2. Integrity is achieved by using access controls and authorization strategies to prevent tampering of data from unauthorized users. Role-Based Authorization provides a good option.
  3. Availability is achieved by establishing rate limits, partial responses and caching in order to prevent extensive usage of API resources or even servers taken down by infinite loops.

7. Use Monitoring and Reporting

While developing and testing your API plays a big part in the process, the real work does not end there. You need to continue providing support even before the code is deployed to production. If something goes wrong, the right people need to be notified with actionable information in order to respond, by any means necessary. This constitutes a proactive approach when developing your API. If you keep things at bay, then when endpoint issues emerge, you can prevent catastrophic failures. API monitoring tools like Runscope can help you with that.


Theo Despoudis is a Senior Software Engineer, a consultant and an experienced mentor. He has a keen interest in Open Source Architectures, Cloud Computing, best practices and functional programming. He occasionally blogs on several publishing platforms and enjoys creating projects from inspiration. Follow him on Twitter @nerdokto. Theo is a regular contributor at Fixate IO.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar