Skip to content

Latest commit

 

History

History
23 lines (14 loc) · 1.84 KB

api-layer.md

File metadata and controls

23 lines (14 loc) · 1.84 KB

📡 API Layer

Use a Single Instance of the API Client

When your application interacts with either RESTful or GraphQL APIs, it is beneficial to use a single instance of the API client that has been pre-configured and can be reused throughout the application. For example, you can create a single API client instance using the native fetch API or libraries such as axios, graphql-request, or apollo-client with predefined configuration settings.

API Client Example Code

Define and Export Request Declarations

Rather than declaring API requests on the fly, it is recommended to define and export them separately.

Declaring API requests in a structured manner can help maintain a clean and organized codebase as everything is colocated. Every API request declaration should consist of:

  • Types and validation schemas for the request and response data
  • A fetcher function that calls an endpoint, using the API client instance
  • A hook that consumes the fetcher function that is built on top of libraries such as react-query, swr, apollo-client, urql, etc. to manage the data fetching and caching logic.

This approach simplifies the tracking of defined endpoints available in the application. Additionally, typing the responses and inferring them further down the application enhances application type safety.

API Request Declarations - Query - Example Code API Request Declarations - Mutation - Example Code