Post originally written by me in Spanish 🇪🇸 on my blog:
VueJS as opposite of Angular, not comes with a predefined way of making HTTP calls. The user can use whatever library of his choice, or not use a library at all. For example, you can make API calls in Vue using the fetch method from Javascript.
Axios is one of the most popular libraries to make API calls and offers abstractions to reduce the code required to make API calls. For example, with axios you don't need to parse the JSON response, and you don't have to pass the base URL of the requests every time.
So, in this article, to learn Axios, we will make an example project using Axios.
Prerequisites
First, you need a Vue project. If you created the project using the vue-cli, the CLI ask you about axios so maybe you alredy have axios installes in your project. To know if you have axios installed, check the package.json and search for the axios package.
If you don't have axios installed you can install it using npm:
npm install axios
Or if you are using Yarn you can use:
yarn add axios
Then you need to have an API with some endpoints. If you don't have one, don't worry cause we are going to use an example API to use in this article.
In this article we're going to use the JSONPlaceholder, feel free to use if you want.
https://jsonplaceholder.typicode.com/
Lastly, you need to know about the basic concepts of Vue. For this article we are going to use the created method from the lifecycle of Vue to make the requests when the component is created. If you want to learn more about Vue lifecycle, check this article written by @samolabams: https://dev.to/samolabams/understanding-vuejs-lifecycle-hooks-5ejk
GET calls
The purpose of a GET is to retrieve information. When you open a page, in the background, the browser sends a GET call to retrieve the page that you are visiting, and the same for all the resources of the page (.css files, images, .js files, etc).
A GET response to an API call usually returns a JSON with the information.
First we are going to create a component that calls the API when is created:
<template>
<div class="content"></div>
</template>
<script>
import axios from "axios";
export default {
created() {
axios.get("https://jsonplaceholder.typicode.com/todos/1").then((result) => {
console.log(result.data);
})
}
};
</script>
<style scoped lang="scss">
</style>
As you can see, we are only importing axios in the component and calling axios.get()
with the url of the JSONPlaceholder API, as simple as this.
Axios returns a promise with the JSON response inside data property parsed for you.
If you create this component you will see in the console of the browser something like this:
If you want to use the response in the view or in another method or computed property you only have to create a new variable inside data of Vue:
<template>
<div class="content">{{ todos }}</div>
</template>
<script>
import axios from "axios";
export default {
data: () => ({
todos: null
}),
created() {
axios.get("https://jsonplaceholder.typicode.com/todos/1").then((result) => {
this.todos = result.data;
})
}
};
</script>
<style scoped lang="scss">
</style>
POST calls
POST endpoints usually are designed to create things. So for example if you want to create a new user in the database almost sure that you will use a POST endpoint to send the info of the new user to create.
POST calls with axios is as simple as GET calls. You only have to call the .post()
method with the URL of the endpoint and a second parameter with the object that you need to pass to the API.
<template>
<div class="content"></div>
</template>
<script>
import axios from "axios";
export default {
created() {
let post = {
title: 'foo',
body: 'bar',
userId: 1
};
axios.post("https://jsonplaceholder.typicode.com/posts", post).then((result) => {
console.log(result);
});
}
};
</script>
<style scoped lang="scss">
</style>
PUT calls
PUT calls are created to edit things or resources in the server. So for example, if you want to edit a user in the database, the logical way to do it is using a PUT call.
PUT calls have the same syntax as in POST, except for the name of the method to call (you only have to call axios.put()
with the URL and the object to edit as second parameter).
created() {
let post = {
title: 'foo',
body: 'bar',
userId: 1
};
axios.put("https://jsonplaceholder.typicode.com/posts/1", post).then((result) => {
console.log(result);
});
}
</script>
DELETE
Delete is to remove resources. With axios you only have to pass the URL of the resource to delete.
created() {
axios.delete("https://jsonplaceholder.typicode.com/todos/1");
}
NOTE: There is also the PATCH methods but I don't use it a lot.
The architecture that I recommend
This is my personal opinion. It may not be the best option for all cases. You have to think if this solution makes sense in your project.
In my case what I do is create a folder inside src called logic in which I create a .js file for each entity. For me entity is something that has a reason to be by itself, for example: users, cars, animals, etc.
Within these files what I do is create a function for each API call, simply returning the request. Let's see an example:
// src/logic.todos.js
import axios from "axios";
const API = "https://jsonplaceholder.typicode.com/todos";
export default {
get() {
return axios.get(API);
},
create(todo) {
return axios.post(API, todo);
}
};
So if you have to use this calls you only have to import this file inside de component to use it:
import todos from "@/logic/todos";
And the use the functions where you want:
async created() {
let response = await todos.get();
console.log(response.data);
}
Note that here I replace the old syntax using then()
for the async / await pattern because is simpler to read.
Conclusions
With the API that we use in this article (JSONPlaceholder) you can create a full website to manage todos so you can practice with all the API calls.
Another thing I recommend is to put the base URL of the API inside the Vue environment variables so you can have the variable stored in one place.
Thanks for reading my post! You can say hello or send me a message in my Twitter @CodingPotions.
Top comments (1)
Good job! :)