Consuming REST APIs
There are different approaches and technologies to consume REST APIs. In this session we are going to use a VueJS application as a consumer of the API that we have developed in our previous session. This is a single page web application. In addition to VueJS, we have used Axios (to make HTTP requests and receive responses) and Vue Router.
- We assume that you have installed NodeJS, npm, and Vue CLI. Detailed instructions on how to install these dependencies, are provided in the previous sessions.
Part 1: POST Request (Add a Publisher):
Complete source code is available here to download: Attach:vue-advera.zip
- Create a VueJS app:
vue create vue-advera- You will see some options, choose
Default ([Vue 3] babel, eslint). - Navigate to your app directory:
cd vue-advera
- Create a VueJS app:
Project Structure
public
src
└── components
│ └── AddPublisher.vue
services
│ └── PublisherDataService.js
App.vue
http-common.js
main.js
router.js
Install required dependencies:
npm install bootstrap@4.6.0 jquery popper.js vue-router axios@4
- Open
src/main.jsand import Bootstrap:
import 'bootstrap' import 'bootstrap/dist/css/bootstrap.min.css'
- If you want to add a set of icons, such as FontAwesome, then follow these steps:
- The easiest way is to use CDN, enter your email here to get started with a free Kit!
- Add the CDN link to head section of
public/index.html
- If you want to add a set of icons, such as FontAwesome, then follow these steps:
<script src="https://kit.fontawesome.com/your-code-number.js"></script>
- Use the regular syntax to use it:
<i class="fa-solid fa-power-off"></i> <i class="fa-solid fa-dove"></i>
- Add Vue Router:
- In
srcfolder, createrouter.jsand define Router as follow:
- In
- Add Vue Router:
import { createWebHistory, createRouter } from "vue-router";
const routes = [
{
path: "/add",
name: "add",
component: () => import("./components/AddPublisher")
},
{
path: "/publishers/:id",
name: "my-publisher",
component: () => import("./components/MyPublisher")
},
{
path: "/",
alias: "/publishers",
name: "publishers",
component: () => import("./components/PublishersList")
}
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
- Open
src/main.jsand import the router in our application:
- Open
import { createApp } from 'vue'
import App from './App.vue'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import router from './router'
createApp(App).use(router).mount('#app')
createApp(App).mount('#app')
- Add a top navigation bar to our application root container (
src/App.vue)
- Add a top navigation bar to our application root container (
<template>
<div id="app">
<nav class="navbar navbar-expand navbar-light bg-light">
<router-link to="/" class="navbar-brand">Advera</router-link>
<div class="navbar-nav mr-auto">
<li class="nav-item">
<router-link to="/publishers" class="nav-link">List Publishers</router-link>
</li>
<li class="nav-item">
<router-link to="/add" class="nav-link">Add Publisher</router-link>
</li>
</div>
</nav>
<div class="container mt-3">
<router-view />
</div>
</div>
</template>
<script>
export default {
name: "app"
};
</script>
- Add
Axiosto consume our Spring Boot REST API:- Make sure the BaseURL has the right host name and port number
- Under the
srcfolder, createhttp-common.jsfile and add the following code:
- Add
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8080/api",
headers: {
"Content-type": "application/json"
}
});
- Create a Data Service that will use axios from HTTP client to send HTTP requests:
- Under
srcfolder, create a new directoryservices - Add the data service file (
PublisherDataService.js) to theservicesfolder - Add the following methods to
PublisherDataService.jsfile:
- Under
- Create a Data Service that will use axios from HTTP client to send HTTP requests:
import http from "../http-common";
class PublisherDataService {
getAll() {
return http.get("/publishers");
}
get(id) {
return http.get(`/publishers/${id}`);
}
create(data) {
return http.post("/publishers", data);
}
update(id, data) {
return http.put(`/publishers/${id}`, data);
}
delete(id) {
return http.delete(`/publishers/${id}`);
}
deleteAll() {
return http.delete(`/publishers`);
}
}
export default new PublisherDataService();
- We need component (VueJS template) to add a new Publisher. This template will accommodate the necessary form components to store the data.
- Create
AddPublisher.vuefile incomponenetsfolder and add the following code:
- Create
- We need component (VueJS template) to add a new Publisher. This template will accommodate the necessary form components to store the data.
<template>
<div class="submit-form">
<div v-if="!submitted">
<div class="form-group">
<h2><i class="fa-solid fa-square-plus"></i> Add a new Publisher!</h2>
<label for="name">Name</label>
<input
type="text"
class="form-control"
id="name"
required
v-model="publisher.name"
name="name"
/>
</div>
<div class="form-group">
<label for="publisher_address">Address</label>
<input
class="form-control"
id="publisher_address"
required
v-model="publisher.publisher_address"
name="publisher_address"
/>
</div>
<div class="form-group">
<label for="publisher_contact">Contact</label>
<input
class="form-control"
id="publisher_contact"
required
v-model="publisher.publisher_contact"
name="publisher_contact"
/>
</div>
<button @click="savePublisher" class="btn btn-primary" type="submit"> Publisher <i class="fa-solid fa-square-plus"></i></button>
<button @click="newPublisher" class="btn btn-warning">Clear <i class="fa-solid fa-eraser"></i></button>
<router-link to="/" class="btn btn-l">Cancel <i class="fa-solid fa-xmark"></i></router-link>
</div>
<div v-else>
<h4>Publisher added successfully!</h4>
<button class="btn btn-success" @click="newPublisher">Add New Publisher</button>
</div>
</div>
</template>
<script>
import PublisherDataService from "../services/PublisherDataService";
export default {
name: "add-publisher",
data() {
return {
publisher: {
id: null,
name: "",
publisher_address: "",
publisher_contact: ""
},
submitted: false
};
},
methods: {
savePublisher() {
var data = {
name: this.publisher.name,
publisher_address: this.publisher.publisher_address,
publisher_contact: this.publisher.publisher_contact
};
PublisherDataService.create(data)
.then(response => {
this.publisher.id = response.data.id;
console.log(response.data);
this.submitted = true;
})
.catch(e => {
console.log(e);
});
},
newPublisher() {
this.submitted = false;
this.publisher = {};
}
}
};
</script>
<style>
.submit-form {
max-width: 400px;
margin: auto;
}
</style>
- Run your application:
npm run serve - Check it on a browser window using
localhost:8081URL - Make sure that your Spring Boot application is running
- Run your application: