How to write a convenient API – 15 recommendations.

How to write a convenient API – 15 recommendations.

Designing a good API requires careful attention to detail and adherence to key API programming principles. Therefore, it is important that developers have the necessary knowledge. My name is Anastasia Ivanova, I work at MTT (part of the MTS ecosystem) as a technical writer for MTS Exolve. In this article, I’ll provide guidelines for creating an API that will help you make it reliable, scalable, and easy to use. The most interesting thing is under the executioner.

General recommendations

  1. Appointment. Before development, clearly define what your API will be used for and what capabilities it should provide. This will help you focus on the key aspects of setting it up. When developing the interface and functionality, design with users’ interests, needs and expectations in mind.

  2. Standardization and security. Follow certain standards and conventions for resource naming, query methods, data format, and error handling. Use popular protocols and standards (REST or GraphQL), and choose a data format that is convenient for you (JSON or XML).

  1. Data protection. Implement authentication and authorization mechanisms to prevent unauthorized access to user information. For example, we use Bearer Token for authentication for requests to our API.

  2. Productivity. Optimize your API to perform requests quickly and efficiently. Cache frequently requested data to avoid repeating the same requests and reduce server load.

  3. Support. Provide channels of communication with users where they can ask questions, report errors, and receive sound advice on how to use your product. The best way to support is the community. Don’t know what to do, ask on the forum.

  4. Version control, testing and debugging. Develop a version control system for your API to ensure backward compatibility and seamless changes without breaking the interface for existing customers. Let the system work as a standalone tool.

  5. Constant updating of documentation. After making changes to the product and testing, you should immediately take care of the relevance of specific API description pages. The best way to achieve this is to make documentation a fundamental part of development. Two well-known tools, Swagger and Postman, help with this and are available for most API development environments.

  1. Testing. Systematically test the API under different scenarios and error handling. Fix detected problems and improve its stability.

  2. Scaling. Consider this capability of your API as the number of users and the volume of requests grow. Use horizontal and vertical scaling, caching, and other techniques to ensure responsiveness and reliability.

Here are even more guidelines for creating APIs. You may also need the Google JSON Style Guide.

Tips for building a user-friendly API

Name agreements

There are differences in nomenclature and styles. Access points and input/output parameters can be written in different ways: camelcase, hyphen, underscore. When creating an API, you should choose one writing style.

Uniformity in syntax will help avoid confusion in code and documentation. And it will be easier for users to read the documentation and use your API in the development of their projects.

Versions

It’s quite common for APIs to change after the initial release. Developers add new functions to the service, new methods and access points appear. Also, developers make improvements to already existing methods that users could use in their projects. If you know your API will change, it’s a good idea to use versioning first. One of the most commonly used methods is to use the Latin letter V (v + version number) in the access point.

example

Note that you should notify your users about the upgrade. It’s also a good idea to maintain the previous version of the API so that your users’ projects will continue to work while they migrate to the new version.

Use HTTP status codes

A valuable feature available in HTTP is status. It is returned in the server response depending on the result of the action sent in the request. There are several types of status: 200 OK (successful request) and error (code 400, 401, 500 and others). If the request is successful, your API should return a 200 OK status. If not, you should give an error status and an explanation so that the user understands what was wrong with his request. Example:

  1. creation voice SMS:

HTTP/1.1 200 OK
Content-Type: application/json

{
    "id": "cal55094238-bc5f-4b2d-8a95-5a20d7cbb5bc"
}
  1. Invalid request:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
    "error": "failed to parse token" // неправильно указан токен приложения
}

All HTTP response codes can be found in the Mozilla documentation.

Use pagination and filtering for end-user convenience

Applications grow over time, and it’s important to give API consumers the ability to get only what they need, without too much information. To do this, break the interface into pages. You can sell it competently with the help of identifiers. Example:

1. GET v1/product?limit=100
2. POST v1/GetList
{
    "limit": 40;
    "offset": 100
}

Use API caching to increase performance

Cache memory effectively relieves the main database of unnecessary load. The main problem with the approach is that data can become out of date, so installing the latest version should sometimes be considered.

Using a cache is useful when loading configurations and directories that don’t change many times over a long period of time. When using the cache, don’t forget to include the Cache-Control information in the headers. This will help to use the system more efficiently.

An example of Python code using the Flask-Caching library and Redis as an external cache:

from flask import Flask 
from flask_caching import Cache
import requests

app = Flask(name)
cache = Cache(app, config={'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': 'redis://localhost:6379/0'})

@app.route('/api/data')
@cache.cached(timeout=60) # кеширование на 60 секунд
def get_data():
response = requests.get('https://api.example.com/data')
return response.json()

if name == '__main__':
app.run() 

In this example, when /api/data is accessed, the cached result is checked. If there is a result, it is returned from the cache. If there is no result, a request is made to https://api.example.com/data, the result is cached for 60 seconds and returned to the client.

Write clear documentation

Writing good documentation is essential to any API development, so it’s one of the key components of our SMS API.

Based on the documentation, developers will integrate your API into their projects. API documentation often includes multiple sections. Example:

  1. Where to start – a brief description of how to start working with the API (authentication method, basic methods)

  2. API Reference — description of all available methods

  3. Instructions – a step-by-step description of how to implement a certain functionality

Each section has its own value, but the most important is the API Reference. It is the Reference that contains the information needed to interact with the API:

  • authentication method

  • connection point indicating the request method (CRUD: GET, PUT, POST, DELETE)

  • input and output data fields

  • possible errors

  • examples of requests

Links to API building guides

  1. An introduction to Mozilla’s Web API for beginners

  2. Tutorial Building Web APIs with ASP.NET Core from Microsoft

  3. Designing a RESTFUL web API from Microsoft

Creating your own API is a difficult task, but by following the key rules of its development, you can put into production a reliable, scalable and easy-to-use interface that can simplify the work of developers.

Related posts