API Design and Architecture
Tags: api, webdev, documentation, programming
Published: 2023-08-16 12:02:02



As a developer, the main goal is to produce apps that users can easily use. For this reason, we usually hear words such as: reliable, scalable, fast, etc. All that to say, you have to build great apps which also means you have to know a lot about how to do it.


In our digital world, good application performance is vital, ensuring seamless user experiences. As apps rely more on web APIs to communicate with external services, API performance becomes crucial. Factors like low latency, high throughput, scalability, caching, and error handling influence API efficiency. Balancing these elements ensures apps run smoothly by interacting effectively with APIs in today’s interconnected landscape.

Now let’s dive deeper into the first step of web API performance optimization, which is to design your API with performance in mind.

There are many points to discuss on this subject but we will deal with the most important in my opinion.

**RESTful Design, Versioning, Response Size and Format, Caching Headers, Logging and Monitoring.**

---

- RESTful Design:

Rest is a type of architectural that provides some standards and/or conventions that must be followed by an API to be called a RestFull or a Rest API.

In 2000, An American computer scientist Roy T. Fielding proposed Rest witch stands for “Representational State Transfert” for building distributed systems based on hypermedia and it aims to facilitate communication between apps.

Rest has 6 standards that a Rest API must follow:

> Separation of the client and the server

This approach means that server and client are managed separately and are only linked by communication. Thus, the client can be of any type. Rest API server could be builded using “Python FastAPI” and the client using “ReactJs”.

> Statelessness

Communication between client and server does not consider the session state from one request to another because each request is self-sufficient.

> Uniformity of the interface

The Uniform Interface constraint subdivides into distinct elements that establish a reliable and foreseeable communication pattern between clients and servers. Here are the main components of the Uniform Interface constraint in a REST API:

**Resource Identification in Requests**: Each resource is identified by a unique URI

**Resource Manipulation Through Representations**: Resources are represented in a standardized format, such as JSON or XML.

**Self-Descriptive Messages** : Every message (request or response) must carry sufficient information for the recipient to grasp its intent, including metadata, headers, and a clear representation format.

**Hypermedia as the Engine of Application State (HATEOAS)** : The server embeds hypermedia links in responses, directing clients toward potential next steps. Clients utilize these links to traverse the application’s states.

> Caching

Implementing caching mechanisms can significantly improve API performance by serving frequently requested data from memory rather than generating it anew each time.

> Layered architecture

In REST APIs, interactions and replies span various tiers. It’s essential to avoid assuming direct client-server connections; intermediaries often come into play. REST APIs must be crafted to be agnostic about whether they engage with the end app or an intermediary in the communication loop.

> Code on demand (optional)

Typically, REST APIs dispatch static resources, yet on occasion, responses might carry executable code (e.g., Java applets). In such instances, the code should solely execute when prompted.

To put it simply, the RestFull Design:

— Follow the principles of representative state transfer (REST) to design simple, intuitive, and resource-oriented APIs.
— Use standard HTTP methods (GET, POST, PUT, DELETE) appropriately to perform CRUD (Create, Read, Update, Delete) operations.
— Use meaningful resource URLs and adopt a consistent naming convention.

> Versioning

Versioning for web API design involves offering a means to handle modifications and updates to your API while upholding backward compatibility. It empowers you to introduce fresh features, adjust current functionality, or retire specific capabilities, all without disrupting existing client apps reliant on your API. Versioning plays a pivotal role in ensuring a seamless experience for developers utilizing your API and the end-users of their applications.

There are several approaches to versioning APIs:

**URL Versioning:**

Example:

`/v1/resource`
`/v2/resource`

Pros:

Easy to understand and implement.
Clear separation between different versions.

Cons:

Clutters the URL space, especially if multiple resources need versioning.

Potential issues with caching and reverse proxy configurations.

**Header Versioning:** It means including the version information in the HTTP headers of the request or response

For example:

`Accept: application/vnd.myapi.v1+json`
`Accept: application/vnd.myapi.v2+json`

Pros:

Keeps the URL cleaner.
Allows for easier integration with client libraries.

Cons:

Developers need to be aware of and handle the versioning in their code.
Slightly more complex implementation.

**Query Parameter Versioning:**

Version information is included as a query parameter in the URL.

For example:

`/resource?v=1`
`/resource?v=2`

Pros:

Allows clients to easily switch between versions.

Cons:

Can lead to issues with caching and search engine indexing.
Can make URLs less readable.

API versioning holds utmost importance in design, wielding substantial influence over your API’s long-term maintainability and user-friendliness. Selecting a versioning approach that harmonizes with your API’s objectives and is effectively conveyed to your developer community is vital.

> Response Size and Format

Keep response payloads as small as possible by only including necessary data fields.

Choose a compact data format, such as JSON, and minimize unnecessary whitespace.

Avoid sending excessive metadata in responses.
Implement pagination for large datasets to avoid sending all data in a single response.

Use query parameters (e.g., ?page=2&limit=10) to control the number of items per page and the current page.

Provide the ability for clients to specify which fields they need in the response (field selection).

Use query parameters (e.g., ?fields=name,email) to customize response content.

> Caching Headers

Caching headers, HTTP headers employed to manage caching actions for resources shared between clients (like web browsers or API users) and servers, play a pivotal role.
 Caching bolsters web app performance by curbing the necessity to continually fetch identical resources from the server.

By configuring suitable caching headers, you wield control over how resources are retained and reused by clients and intermediate caches, including proxy servers and content delivery networks (CDNs).

> Logging and Monitoring

**Logging**: Involves recording events, errors, and relevant information about the interactions and activities of your API.
 These logs serve as a historical record that can be used for debugging, auditing, and understanding how your API is being used.

**Monitoring**: Involves the continuous observation of key metrics and indicators related to your API’s performance, availability, and usage. Monitoring helps you proactively identify performance bottlenecks, downtime, and anomalies, allowing you to take corrective action in a timely manner.

Bear in mind that crafting an efficient API revolves around harmonizing simplicity, flexibility, and efficiency.

As you center your efforts on these design tenets, stay open to adjustments and refinements to align with the shifting usage patterns and needs of your API.

I hope you will find this article useful.
See you soon 🙃

Follow me there :

https://www.linkedin.com/in/laetitia-christelle-ouelle-89373121b/

https://ouelle.medium.com/