How to use API in Node js

WHAT IS API

API stands for Application Programming Interface, which defines interactions between software intermediates. It defines the kind of calls or requests made and how data is reached. The Major format of data received is JSON and sometimes XML. We can access this data and use it in portraying the website. There are innumerous API nowadays and used for may purpose

eg:-

  1. location and maps-Google map API
  2. weather – open weather map API
  3. Payment – PayPal API
  4. we can create restful API we created in CRUD in the previous tutorial.

There are certainly more things that we can fo with API. Every API has it’s own set of documentation that explains the flow of data and structure of parameters and objects. So to use any API we have to thoroughly read the documentation and study the response.

We will build a simple weather app using Open weather maps:- https://openweathermap.org/

SetUp the Folder Structure:-

  • Create a Root directory “weather-api”
  • Create an app.js file.
  • Views Folder for all the template and rendering pages
  • package-json is created when we initialized the project.

Get API KEY

  • All keys are unique for the user and can be found on the official website easily
  • To get API key login to https://openweathermap.org/  Or Sign up and get the key.
  • Copy that key and store it until we use it in the program.
  • The Red box contains the API key and it’s a private key so try storing it in an environment variable.

Example to use API in Node js

Setting Up app.js File And Routes

  • Initialize the project and install express and setup the server to listen to a localhost port.
  • Install and require all the dependencies needed.
    PS D:\work\Codebun\Weather_api>npm i request body-parser express
  • Save the API key in a variable and use the middleware to use body-parser and public files.
  • Set up a get route for “/” that is for the home page that will render the index.ejs file which will be the HTML template of our weather app page.
  • Set up a post request so that the user can enter the city name to find it’s the weather.
  • Extract the city from the body as the user will submit the format and set up URL using the API-key and city name.
  • send the request to URL along with two more parameters they are response and error.
  • Check for the error if error found then return the index page with weather null and a message
  • Else set parse the JSON in weather variable.
  • Check as per the document condition if weather available if not again return weather not found
  • Else extract the weather from parameters and save in a variable and send as an object along when rendering index.js.

Code:-

const express = require('express');
const app = express();
const request = require('request');
const bodyParser = require('body-parser');

const apikey="xxxxxxxxxxxxxxxxxxxxxxxxx"; //put your api key here

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.set('view engine', 'ejs');

app.get("/",(req, res)=>{
        res.render("index");
})

app.post('/', function (req, res) {
    let city = req.body.city;
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${apikey}`;
  
    request(url, function (err, response, body) {
      if(err){
        res.render('index', {weather: null, error: 'Error, please try again'});
      } else {
        let weather = JSON.parse(body)
        if(weather.main == undefined){
          res.render('index', {weather: null, error: 'Error, please try again'});
        } else {
          let weatherText = `It's ${weather.main.temp} degrees FAHRENHEIT
          in ${weather.name}!`;
          res.render('index', {weather: weatherText, error: null});
        }
      }
    });
  })

app.listen(2500,()=>{
    console.log("Server started at port 2500");
});

Index.ejs/views

  • Getting Boilerplate code of HTML set title.
  • Create a container and a fieldset for the content to display
  • Create a form to enter the city name and set the method to post and action to homepage index “/”.
  • Use the embedded javaScript to check weather has and display temperature and overall weather of the town.
  • It will re-render the index asking for the city if the city wasn’t found.

Code:-

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Weather-Api</title>
    <link rel="stylesheet" type="text/css" href="/css/style.css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
  </head>
  <body>
    <div class="container">
      <fieldset>
        <legend><strong>KnowWeather:</strong></legend>
        <form action="/" method="POST">
          <input name="city" type="text" placeholder="Enter a City" required>
          <input type="submit" value="Get Weather">
        </form>
        <% if(weather !== null){ %>
            <p><%= weather %></p>
          <% } %>
  
          <% if(error !== null){ %>
            <p><%= error %></p>
          <% } %>
      </fieldset>
    </div>
  </body>
</html>

OutPut:-