
Member-only story
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.js