API Handling: Utilizing the Facade Pattern with Axios in Frontend Development
Tags: typescript, frontend, webdev, ui
Published: 2024-04-25 15:41:56


![Facade Pattern](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3z765w7wg4xavpil7vt.png)

Hello everyone! Today, I'd like to share a code pattern for interacting with APIs from the frontend. I recently came across this pattern and found it quite interesting.

Typically, there are various ways to choose an HTTP client, and for this example, I've chosen [axios](https://axios-http.com/).

#### **`api.ts`**
```ts
import axios from 'axios';

const PUBLIC_API_URL="localhost:3000"

const METHOD: Record<string, string> = {
	GET: 'get',
	DELETE: 'delete',
	POST: 'post',
	PUT: 'put',
	PATCH: 'patch'
};

const axiosAPI = axios.create({
	baseURL: PUBLIC_API_URL
});

const apiRequest = async (
	method: string,
	url: string,
	request?: Record<string, any> | undefined
): Promise<ApiResponse> => {
	const headers = {
		Authorization: 'Bearer some_token',
        };

	return await axiosAPI({
		method,
		url,
		data: request,
		headers
	}).then((response) => {
		// handle a loading or something like that
		return response?.data;
	});
};

const get = (url: string, request?: Record<string, any> | undefined) =>
	apiRequest(METHOD.GET, url, request);

const post = async (
	url: string,
	request?: Record<string, any> | undefined,
) => {
	const response = await apiRequest(METHOD.POST, url, request);
        // show modal or something like that

	return response;
};

const patch = async (
	url: string,
	request?: Record<string, any> | undefined,
) => {
	const response = await apiRequest(METHOD.PATCH, url, request);
        // show modal or something like that
 
	return response;
};

const deleteRequest = async (url: string, request?: Record<string, any> | undefined) => {
	const response = await apiRequest(METHOD.DELETE, url, request);
        // show modal or something like that

	return response;
};

const put = (url: string, request?: Record<string, any> | undefined) => {
        const response = apiRequest(METHOD.PUT, url, request);
        // show modal or something like that

	return response;
}

const API = {
	get,
	delete: deleteRequest,
	post,
	put,
	patch
};

export default API;
```
From the code snippet, you can see that we encapsulate concerns like authorization, endpoint URLs, and modal display within a single file.

How to use this class is
#### **`example.ts`**
```ts
import Api from './api'; // import api class

const responses = await Api.get(`/warranty/${serialNumber}`);
// handle data or something like that
console.log(response)
```

The usage of this class is straightforward. You can see from the example.ts file how easy it is to call API methods without worrying about authorization, endpoint URLs, or modal displays, as these complexities have been abstracted away into the `api.ts` file.

This approach aligns well with the [Facade Pattern](https://github.com/saladpuk/design-patterns/blob/master/Facade.md).

The benefits of adopting this coding style include making the code easy to understand and efficient, allowing everyone on the team to grasp it quickly and use it without needing to spend time studying or modifying the code.

Additionally, splitting the code into smaller parts also improves testing efficiency.

Finally, utilizing the Facade Pattern helps maintain a structured and convenient maintenance process for the project.

Next time, I'll share how to handle cases where we call the same GET endpoint but need to handle different data. Stay tuned!