Skip to main content

Building a API Client for VueJS

Hello!
In this post i will show you how you could create a simple API Client service to use in your VueJS application so you could easily make HTTP Server calls from your app.
First, make sure to install the Vue-resource module in your app using npm or yarn like:
npm install vue-resource --save
Then, import it into your main.js file, like below:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
// import vue-resource module
import VueResource from 'vue-resource'
Vue.config.productionTip = false
// use the vue-resource module
Vue.use(VueResource)
new Vue({
router,
render: h => h(App)
}).$mount('#app')
view raw main.js hosted with ❤ by GitHub
Now, create a new file named api-client.js, put it in a directory called "services" and add the code:
import Vue from 'vue'
export default class ApiClient {
static callAPI (method, url, data) {
const options = {
method: method,
url: `${process.env.VUE_APP_API_URL}/${url}`,
headers: {
'Content-Type': 'application/json'
}
}
// add the block below, if you want to add authentication
// get the local user token to authenticated requests
let localUser = localStorage.getItem('mylocaluserwithtoken')
if (localUser) {
localUser = JSON.parse(localUser)
if (localUser.token) {
options.headers['Authorization'] = `Bearer ${localUser.token}`
}
}
if (data) {
options.body = data
}
return new Promise((resolve, reject) => {
Vue.http(options).then(resp => {
resolve(resp.body)
}).catch(err => {
reject(err)
})
});
}
static apiGet (url) {
return this.callAPI('GET', url)
}
static apiPost (url, data) {
return this.callAPI('POST', url, data)
}
static apiPut (url, data) {
return this.callAPI('PUT', url, data)
}
static apiDelete (url) {
return this.callAPI('DELETE', url)
}
}
view raw api-client.js hosted with ❤ by GitHub
The code is self explaining and you can modify it as your needs. Now, you only need to use your ApiClient anywhere in your application. Below, i'm giving you a sample of using it in a Login component.
<template>
<div class="login">
<form>
<div>
<label for="">E-mail</label>
<input type="email" v-model="user.email"/>
</div>
<div>
<label for="">Password</label>
<input type="password" v-model="user.password"/>
</div>
<input type="submit" value="Login"/>
</form>
</div>
</template>
<script>
import ApiClient from '@/services/api-client'
export default {
data () {
return {
user: {
email: '',
password: ''
}
}
},
methods: {
submit () {
ApiClient.apiPost('user/login', user).then(resp => {
// User authenticated!
});
}
}
}
</script>
view raw Login.vue hosted with ❤ by GitHub
Hope you enjoy!

Comments

Popular posts from this blog

Connecting to a serial port on MAC OS

Sometimes you need to connect to the serial port of a device from your MAC OS computer. It's pretty simple, first you need to list all your serial ports using the command: ls /dev/tty* Then, find the device name you want to connect to and type the command: screen /dev/tty[DEVICE_NAME] , In the example above, if you want to connect to the tty.usbserial device, you will type in your terminal: screen /dev/tty.usbserial Type enter, wait some seconds and you will be connected to the device serial port!

Node.js async functions error handling

If you come from start of Node.js, you probably remember that the callback functions had always by convention a error as it's first parameter and the result as the second one. Now days, most people use async functions instead of callbacks because they leave the code more clean and are usually easier to understand by someone that comes from programming in other languages. In my opinion, a problem that exists when using async functions is the error handling. Usually people use try / catch blocks but there is a better way i will show you now. You could have a wrapper function or handler function that always return a pattern like in callback functions, this is, a error as first and a result as second parameter. Take a look at the gist below so you could understand what i'm talking about: I created a function that validates if the user input is the number one (1). If it's valid, it returns the message "OK" and if it's not, it returns the error message saying...