Arvutiteaduse instituut
  1. Kursused
  2. 2021/22 kevad
  3. Ettevõttesüsteemide integreerimine (MTAT.03.229)
EN
Logi sisse

Ettevõttesüsteemide integreerimine 2021/22 kevad

  • Home
  • Lectures
  • Practicals
  • Assignements
  • Project and exam
  • Message Board

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

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.js and 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
<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 src folder, create router.js and define Router as follow:
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.js and import the router in our application:
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)
<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 Axios to consume our Spring Boot REST API:
    • Make sure the BaseURL has the right host name and port number
    • Under the src folder, create http-common.js file and add the following code:
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 src folder, create a new directory services
    • Add the data service file (PublisherDataService.js) to the services folder
    • Add the following methods to PublisherDataService.js file:
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.vue file in componenets folder and add the following code:
<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>
      &nbsp;<button @click="newPublisher" class="btn btn-warning">Clear <i class="fa-solid fa-eraser"></i></button>
      &nbsp;<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:8081 URL
  • Make sure that your Spring Boot application is running

  1. Part 2: GET Requests
  2. Part 3: PUT and DELETE Requests
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused