codeburst

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

Follow publication

Member-only story

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.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

--

--

Published in codeburst

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

Responses (15)

Write a response