codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

How to make API calls in a smart way

Francesco Zuppichini
codeburst
Published in
3 min readAug 16, 2017

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

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Responses (15)

Write a response