
How to make API calls in a smart way
By keeping all the endpoints in globally shared file
While developing a web application, we have to make some APIs calls in order to get or update the data we are using. Usually, the calls are called directly into the code, for example.
//some Posts.js file, it can be a React/Angular/Vue component... some stufffetchPosts() { return axios.get('/posts') }
That is a classic snippet where, by using the well know library axios, we are making an API call directly into the component code.
It may happen that in another file we need to do the exactly same request so we just use the same code
//another .js file, it can be a React/Angular/Vue component... some stufffetchPostsAgain() { return axios.get('/posts') }
Usually, developers love copy and paste. This a common situation with redundant code. So if something change in the server, we need to update two functions in two files: that is inconvenient.
Solution #1
Easily, a correct thing to do is to create a file, called api.js where we store a big object with all the endpoints URLS
//api.jsexport default { posts: '/posts'}
Then we can
//some Posts.js file, it can be a React/Angular/Vue componentimport api from './api'... some stufffetchPosts() { return axios.get(api.posts) }
And similarly in the other file
//another .js file, it can be a React/Angular/Vue componentimport api from './api'... some stufffetchPostsAgain() { return axios.get(api.posts) }
Now if we want to change the url, we can just edit one file. But, still, we have some shared code: the axios call.
Solution #2
Let’s actually move all the logic behind calling our web server into the shared file
export default {posts(url) {
return {
getOne: ({ id }) => axios.get(`${url}/${id}`),
getAll: () => axios.get(url),
update: (toUpdate) => axios.put(url,toUpdate),
create: (toCreate) => axios.put(url,toCreate),
delete: ({ id }) => axios.delete(`${url}/${id}`)
}
}
}
Now we can just call api.posts('posts').getAll() in our code.
Solution #3
We can now even expand solution#2 by creating an API class that will create the basic CRUD endpoints for us.
You can find the code here:
https://github.com/FrancescoSaverioZuppichini/API-Class

We can now easily create an API instance
const myApi = new API({ url:'http://localhost:8080/api' })And then create all the correct handles for the posts entity with one line of code
myApi.createEntity({ name: 'posts' })Let’s try if it works! I have a web quote API running at localhost:8080/api/posts
myApi.endpoints.posts.getAll().then(({ data }) => console.log(data))
result
Object {data: Array(4), meta: Object}Perfect! Let’s try to fetch one by id
myApi.endpoints.posts.getOne({ id: 1}).then(({data}) => console.log(data))
And the output
{ author: { id: 1, name: 'Henry Thoreau' },
author_id: 1,
created: 1500208099.04669,
id: 1,
tags: [],
text: 'Things do not change, we change. ',
totalLikes: 0,
user:
{ google_id: '105140920994782382362',
id: 1,
profile_image: 'https://lh6.googleusercontent.com/-IPkTcTumu4Y/AAAAAAAAAAI/AAAAAAAAAAA/AI6yGXxYIjcZrpi_07v27U32SuXjBTAPCg/s96-c/photo.jpg',
user_name: 'Fra Zuppi' },
user_id: 1 }We can also try to create/update and delete a post
const post = { author: { id: 125, name: 'test' },
author_id: 125,
tags: [],
text: 'test',
user:
{ google_id: '105140920994782382362',
id: 1,
profile_image: 'https://lh6.googleusercontent.com/-IPkTcTumu4Y/AAAAAAAAAAI/AAAAAAAAAAA/AI6yGXxYIjcZrpi_07v27U32SuXjBTAPCg/s96-c/photo.jpg',
user_name: 'Fra Zuppi' },
user_id: 1 }myApi.endpoints.posts.create(post)
.then(({ data }) => myApi.endpoints.posts.update(data))
.then(({ data }) => myApi.endpoints.posts.delete(data))
.catch((err) => console.log(err))
Now check the server’s logs

Everything worked as expected. We have successfully create our endpoints for the posts entity.
Conclusion
We have seen how we can improve our application’s code by just sharing global data into a global file. We have seen some solution about the problem and how to automatically create APIs call by using a util class.
I hope you like this article, let me know your feedbacks.
Thank you for reading.
Francesco Saverio Zuppichini

