API’s are great. They let you establish a channel to communicate between two systems which may be built on different platforms & let you send-receive data between them.

API design is an interesting part of software engineering & definitely an extremely important one. Well designed & documented APIs can be like a godsend when you want to integrate & communicate with a service from your app. In Part 1 of this article, we saw what APIs are & why should we use them.

We also learned about some best practices of API design such as

  1. API data modeling & structuring
  2. Writing resource-oriented APIs
  3. Understanding the REST framework
  4. API Versioning
  5. Pagination

Good API Design is not limited to these best practices, but it also involves understanding your target audience, thinking from their perspective & incorporating elements that can make your API as easy to use without causing too many problems to the developers.

Return well-formatted JSON Responses

REST is a popular and widely used architecture for writing APIs. Just as it uses verbs (GET, PUT, POST, etc) to define the type of request that a client makes, REST recommends the JSON format to return the response back to your client.

It is much easier for your consumers to understand and handle JSON responses inside their apps rather than plain-text responses, even though it might seem otherwise. In the same way, it is easier for your API service to understand a JSON request payload than a plain-text one.

For example, for a response as simple as ‘User Logged Out’, use a code-message format of JSON to return your response. We will look at the code part of the response further below but for now, consider the 200 OK status code.

{
    'code': 200,
    'message': 'User Logged Out'
}

The above response is much more structured than returning a plain-text response. Also, always make sure your content-type is set to application/JSON to avoid problems.

Use standard HTTP Status Codes

The HTTP protocol has a well-defined set of status codes that enable you to provide exact information about the status of the request. A quick tip, most apps check for the status code and not the message, since the message can change as per the situation, hence providing the correct status code is extremely important.

The most common HTTP status codes are:

Special note about the difference between 401 & 403 status codes:

When the client is not authenticated, your API should return the 401 status code. But when the client is authenticated (logged in) but does not have the access-clearance level to access said resource.

For example, consider Marvel’s S.H.I.E.L.D, if you just walk into the building and ask for active threats around the world, sorry mate but you’re going to get thrown out with a 401 stamped on your forehead. You’re not an agent, so you’re not allowed to ask for such stuff.

On the other hand, if you are, in fact, a newly recruited Agent of S.H.I.E.L.D, and you ask the same question, you may get an answer. But if you go around asking if you can see the Tesseract, you will not have the clearance level to ask for such stuff, and you’ll be told you don’t have access to this information. A 403 status code.

Error Handling

Often times, developers will face errors while trying to integrate your API into their app, like an invalid/mandatory API key. It is imperative that you give a proper response with the correct error message, else it ends up confusing the developer trying to integrate your API.

An example of a bad error response is:

{
   'message':'Invalid API Key'
}

A good practice while handling such errors is to include a link to your documentation or the page where the developer can generate their API key. This prevents research from the developer side and your pro-activeness makes sure the developer is able to resolve their error quickly.

{
    'message':'Invalid API Key',
    'details': {
        'link': '<LINK TO DOCUMENTATION>',
        'description': 'Your API key is invalid, please re-check your API key or generate a new one from the link above'
    }
}

Allow Asynchronous requests

Sometimes a request might require processing that takes a while to complete. It’s not acceptable to make your client wait for the completion of the request, causing loaders that show for a long time. Apart from the above HTTP codes, there’s another interesting status code that you can use in such a case. Return HTTP status code 202 Accepted to indicate the request was accepted for processing but is not completed.

But, you might wonder how would the client know if the request has completed at all? Ideally, you would want to expose another API endpoint that returns the status of this asynchronous request.

For example, consider you’re trying to download data for a unique ID in your system

API Endpoint: POST /download-data
Request:
{
   'id':<UNIQUE ID>
}
Response:
{
   'code': 202,
   'message': 'Your request is in progress, please check back later.'
}
API Endpoint: GET /download-status
Request:
{
   'id':<UNIQUE ID>
}
Response:
{
   'code': 200,
   'message': 'Request In Progress'
}

If the download-data has been completed, you can either add a link to the file in the response or use an HTTP code 303 meaning the response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource. But this can get complicated quickly, so unless the situation calls for it, I prefer including the link in the response and let the client call the resource link on their side.

If you’d like to know more, here’s an in-depth article for the Asynchronous Request-Reply pattern.

Be open to constructive feedback

All things said and done, as API designers we cannot be absolutely perfect from the start, the more APIs you design and create, the better you will get. Feedback from the developers who consume your API is valuable too, so make sure you reach out once in a while and ask for feedback.

Your customers, the developers who use your API to power their apps can provide better insight on how your API can be improved over time. You can ask for feature requests and notify developers of bug fixes and versions. This helps you build an active developer community that participate actively in the development & design of your API Product.

There you go! The above best practices are guidelines to make your APIs easy to understand and integrate. However, it is okay to diverge from the best practice guidelines as per your business requirements.

#backend #programming #code #software-development #api

Best Practices: API Design [Part 2]
1.30 GEEK