API Client Documentation for React + Redux Application
This document explains the structure and usage of the queryAsync
function, your custom API client in the React + Redux application.
Purpose:
- Provide a centralized and consistent way to make API requests from your React components.
- Simplify API interactions by handling URL construction, headers, and error responses.
Key Features:
- Type-safe: Enforces specific types for request and response data using interfaces.
- Token handling: Optionally includes an access token in the Authorization header for authenticated requests.
- Query parameter serialization: Automatically constructs the API URL with any provided query parameters.
- Error handling: Returns a normalized error object in case of API failures.
- Flexibility: Supports various HTTP methods (
type
), request data (data
), and timeout configuration.
Function Breakdown:
queryAsync
:- Accepts an
ApiClientRequestType
object containing details about the API request. - Uses
axios
library to make the actual HTTP request. - Serializes the API URL with base URL and query parameters using
serialize
function. - Includes access token in Authorization header if provided.
- Parses the API response and resolves with data on success or rejects with a normalized error object on failure.
- Accepts an
Request Types:
path
: Endpoint URL relative to the base URL.type
: HTTP method (e.g.,GET
,POST
,PUT
, etc.).data
: Optional data to be sent in the request body.queryParams
: Optional object containing query parameters.token
: Optional access token for authenticated requests.additionalHeaders
: Optional object for additional headers.timeout
: Optional timeout value for the request in milliseconds.
Response:
- On success, resolves with the parsed data object from the API response.
- On failure, rejects with an error object containing
errorCode
anderrorMessage
.
Usage Example:
javascript
const getBlogPosts = async () => {
const response = await queryAsync({
path: '/api/blogs',
type: 'GET',
});
// Use the response data (array of blog posts) in your component
};
Benefits:
- Improved code organization and reusability for API interactions.
- Centralized error handling for consistent user experience.
- Enhanced type safety and maintainability.
Additional Notes:
- Refer to the
api
constant file for base URL and other API-related configurations.