Manage your API calls like a pro!

JC.log
3 min readMar 6, 2021

Today we will look into a way to manage API calls from front end.

In a considerably big app or website, we have to call a lot of APIs, which can be a pain if not handled properly. And can feel like …

API calls can contain many operations like Create, Read, Update, Delete etc…So for this tutorial purpose, I am considering CRUD operations on an entity.

Okay, now you will think what is entity here?🤔

Here, an entity could be a user👥 or a product📦 or anything on which you perform CRUD operations.

Okay now let’s go into the implementation⛏️.

We will create two files to manage our API calls.
1. entity.js (This file will contain API calls related only to this specific entity)
2. api.js (Here we will combine all our entity API calls)

This is how our entity.js file will look. (Here “entity” will be replaced by the name of entity)

entity.js

export const addEntity = () => {
...
};
export const fetchEntity = () => {
...
};
export const updateEntity = () => {
...
};
export const deleteEntity = () => {
...
};

See how we are exporting all the functions from the file.

api.js

import { addEntity, fetchEntity, updateEntity, deleteEntity } from "./entity.js";export const entityAPI = {
addEntity: () => addEntity();
fetchEntity: () => fetchEntity();
updateEntity: () => updateEntity();
deleteEntity: () => deleteEntity();
};

That’s it, this is what we need.
Now we can call our API functions by importing this entityAPI variable from api.js file.

<script>
import { entityAPI } from "./api.js";
const fetchEntity = async () => {
const response = await entityAPI.fetchEntity();
console.log(response);
};
</script>

Just like this, we can have many entities combined in api.js file.

import { addEntity, fetchEntity, updateEntity, deleteEntity } from "./entity1.js";
import { addEntity, fetchEntity, updateEntity, deleteEntity } from "./entity2.js";
export const entity1API = {
addEntity: () => addEntity();
fetchEntity: () => fetchEntity();
updateEntity: () => updateEntity();
deleteEntity: () => deleteEntity();
};
export const entity2API = {
addEntity: () => addEntity();
fetchEntity: () => fetchEntity();
updateEntity: () => updateEntity();
deleteEntity: () => deleteEntity();
};

Here is a more practical use-case.

user.js
api.js

Advantages:
1. Keeps different files for different entities (Easy to manage)
2. All APIs are accessible through one file, still are separated by there own object variables.

Disadvantages:
1. If you want to change anything, you will have to change it in both files.
2. api.js file can become a bit long if you have way too much entities.

Thank you for reading until this point. Make sure to leave a comment for any suggestions and 👏 for this story.

--

--

JC.log

Just an average guy, showing average coding content.