Open In App

REST API Call to Get Location Details in Vue.js

Last Updated : 04 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will know the REST API call to get the location details in VueJS, along with understanding its implementation through the examples.

VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developer. It is compatible with other libraries and extensions as well. If you want to create a single-page application then VueJS is the first choice in my opinion. In the development field, there may be so many issues that can not be solved by using a single library, so the VueJS is compatible with other libraries so you can easily go for it. The VueJS is supported by all popular browsers like Chrome, Firefox, IE, Safari, etc. You can easily compare this library with your favorite libraries.

REST stands for REpresentational State Transfer. REST is an architectural style for creating websites using the HTTP protocol. There are certain architectural constraints that developers should follow when building websites or APIs. A REST API is also called the RESTful API, is an application programming interface that adheres to the constraints of REST architectural style and enables interaction with RESTful web services. Interconnected networks make up the web. A web service is a set of open protocols and standards used for exchanging data between client-server applications. Web services that follow the REST architecture are known as RESTful web services. The REST API Call is a call request made by the client or users to the server, in order to receive back the data over the HTTP protocol. The API (Application Programming Interface) is a set of commands, functions, or protocols that act as an intermediary that enables two applications to communicate. The Google Map API can be used to get the location detail ie., they facilitate the user to get their location to web applications, based on the requirement. The API interacts and provides the response mostly in JSON or XML formats. Java Script Object Notation(JSON) is an open standard file format and data interchange format.

Steps to set up the Vue JS framework with the required packages:

Here, we will clone or download the application from an already created GitHub repository. All these installations & cloning or downloading will be done in the same folder or the same working directory. Please refer to the Vue.js article for creating a new project in detail.

Step 1: We must have installed npm in the local system. Cloned or downloaded the project, once it is done, go to the project location where package.json is present and need to give the below command

npm install

To check npm is installed or not run the below command:

npm -v

Step 2: Download the Node JS from the official website. To check whether the node is properly installed or not, run the below command:

node -v 

Step 3: Install Vue Cli Node Package Globally using the following Command:

npm install -g @vue/cli

Step 4: Cloning and Running the Application

After installing the npm & all other related packages, place the source code folder in the current or same working directory. Once this is done, we can see that node_modules will be available in the project directory. Now, run the following command to run the application.

npm run serve

The Application runs & hosted to localhost:8080.

Project Structure: After successful installation, the project structure will be displayed as the following image:

REST API Call getting used:

We will use this REST API call link https://api.zippopotam.us/in/600028 ib our project.

Here, 600028 is the Zip Code value for which the data is retrieved, but inside the code, the user can able to input the zip code and get details.

JSON Output:

Example: This example illustrates getting the location details through the REST API Call using the VueJS.

This is in the root directory

package.json:

Javascript




{
  "name": "RestAPIInvocation",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "test:unit": "vue-cli-service test:unit",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d dist"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "bootstrap-vue": "^2.0.0-rc.11",
    "vue": "^2.5.16",
    "vue-router": "^3.0.1",
    "gh-pages": "^1.2.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.0.0-rc.10",
    "@vue/cli-plugin-eslint": "^3.0.0-rc.10",
    "@vue/cli-plugin-unit-mocha": "^3.0.0-rc.10",
    "@vue/cli-service": "^3.0.0-rc.10",
    "@vue/test-utils": "^1.0.0-beta.20",
    "chai": "^4.1.2",
    "vue-template-compiler": "^2.5.16"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": ["plugin:vue/essential", "eslint:recommended"],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": ["> 1%", "last 2 versions", "not ie <= 8"]
}


main.js




import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import BootstrapVue from "bootstrap-vue";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-vue/dist/bootstrap-vue.css";
  
Vue.config.productionTip = false;
Vue.use(BootstrapVue);
  
new Vue({
  router,
  render: (h) => h(App),
}).$mount("#app");


App.vue




<template>
  <div id="app">
    <router-view />
  </div>
</template>
  
<style>
  #app {
    font-family: "Avenir", Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
  }
  #nav {
    padding: 30px;
  }
  
  #nav a {
    font-weight: bold;
    color: #2c3e50;
  }
  
  #nav a.router-link-exact-active {
    color: #42b983;
  }
  
  .centeralign {
    display: block;
    margin-left: auto;
    margin-right: auto;
  }
</style>


router.js: Main.js file to inform where to look for the view file and get the details.

router.js




import Vue from "vue";
import Router from "vue-router";
import detailsByZipCode from "./views/detailsByZipCode.vue";
import getExchangeRates from "./views/getExchangeRates.vue";
Vue.use(Router);
  
const router = new Router({
  routes: [
    {
      path: "/",
      redirect: "/detailsByZipCode",
    },
    {
      path: "/detailsByZipCode",
      name: "detailsByZipCode",
      component: detailsByZipCode,
    },
    {
      path: "/getExchangeRates",
      name: "getExchangeRates",
      component: getExchangeRates,
    },
  ],
});
export default router;


detailsByZipCode.vue




<template>
    <div class="home">
        <div class="vue-logo-back">
            <img src="../assets/logo.png"
                 width="100px" 
                 height="100px" />
        </div>
        <div class="col-md-6 centeralign">
            <p>
                This Page Displays Country details 
                by Zip Code. Example : 600 028
            </p>
            <input type="text" 
                   v-model="input.zipcode" 
                   placeholder="Zip Code" />
            <button v-on:click="getLocationDetails()">
                Get Location Details
            </button>
            <div class="card-body">
                <h5 class="card-title">
                    {{countrydetails["post code"]}}
                </h5>
                <p class="card-text">
                    Zip Code : {{countrydetails["post code"]}}
                </p>
  
                <p class="card-text">
                    Country : {{countrydetails.country}}
                </p>
  
                <p class="card-text">
                    Country Short Form : {{countrydetails["country abbreviation"]}}
                </p>
  
                <ul>
                    <li v-for="place in countrydetails.places" :key="place.longitude">
                        <p class="card-text">
                            Place Name : {{place["place name"]}}
                        </p>
  
                        <p class="card-text">
                            Longitude : {{place["longitude"]}}
                        </p>
  
                        <p class="card-text">
                            Latitude : {{place["latitude"]}}
                        </p>
  
                        <p class="card-text">
                            State : {{place["state"]}}
                        </p>
  
                        <p class="card-text">
                            State Short Form : {{place["state abbreviation"]}}
                        </p>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</template>
  
<script>
import axios from 'axios'
  
export default {
    name: 'countrydetails',
    // Fetch the call for default Zip code 
    mounted(){
        axios.get(`https://api.zippopotam.us/in/600028`)
        .then(response => { 
            this.zipcode = response.data.origin;
            this.countrydetails = response.data;
        }).catch(error => { 
        })
  
    },
    data() {
        return {
            input: {
                zipcode: ""
            },            
            countrydetails: {}
        }
    },
  
    methods: {
        // According to the given zipcode, the fetch is happening
        getLocationDetails() {
            axios.get(`https://api.zippopotam.us/in/`+this.input.zipcode)
            .then(function(response)  { 
                this.countrydetails = response.data;
            }.bind(this)).catch(error => { 
            })            
        }
    }
}
</script>
<style scoped>
  .addmargin {
      margin-top: 10px;
      margin-bottom: 10px;
  }
  
  .vue-logo-back {
      background-color: black;
  }
</style>


Under the “public” folder, we need to place the required images, index.html.

index.html




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <link rel="icon" 
          href="<%= BASE_URL %>india.png">
    <title>
        Finding Area Details By ZipCode 
    </title>
</head>
  
<body>
    <noscript>
        <strong>
          We're sorry but simple-vue-app doesn't 
          work properly without JavaScript enabled. 
          Please enable it to continue.
        </strong
    </noscript>
    <div id="app"></div>
</body>
</html>


Output:

 

In the code example, the zip code is hardcoded while loading, but users can input the zip code and get location details for other Zip codes too. In case, if there is a necessity to develop multiple Rest API calls, “router.js” should have the necessary details. Add necessary view files and in that appropriate Rest API call has to be given and then iterate the JSON response.

Few other REST APIs:

  • https://api.exchangerate-api.com/v4/latest/INR -> Provides the exchange rates of other currencies in USD, GBP, etc.,
  • https://api.coinbase.com/v2/currencies -> Currency code and names

GitHub Link: https://github.com/raj123raj/RestAPIInvocation.git



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads