Web APIs

Web APIs

APIs consist of:
  • endpoints
  • paths
  • parameters
  • authentication
Example of endpoint is the root path of a website used to get back a JSON document (example: https://api.kanye.rest).
API paths and parameters: Path is after the endpoint. Paths are pre-planned by the web application owner. That's where parameters come in. ?blacklistFlags=nsfw&type=single is an example from the Joke API. The order of the parameters doesn't matter.
To limit the use of data or monetize, web app developers use authentication. Typically these consist of keys issued to programmers.
Example of using an API (OpenWeatherMap):
index.html:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>

<body>
    <form  action="/" method="post">
        <label for="cityInput">City Name:</label>
        <input id="cityInput" type="text" name="cityName">
        <button type="submit">Submit</button> 
    </form>
</body>

</html>
app.js (uses Express.js and a few modules):
const express = require("express");
const app = express();
const https = require('https');
const bodyParser = require('body-parser');


app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});

app.post("/", function (req, res) {
    console.log("Post request received");
    const query = req.body.cityName;
    //const apiKey = "<your api key>";
    const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&units=imperial&appid=" + apiKey;

    https.get(url, function (response) {
        console.log(response.statusCode);
        response.on("data", function (data) {
            const weatherData = JSON.parse(data);
            console.log(weatherData);
            const temp = weatherData.main.temp;
            const description = weatherData.weather[0].description
            console.log(temp);
            console.log("Weather description is " + description);
            const icon = weatherData.weather[0].icon
            console.log("Icon is " + icon);
            const imageURL = "http://openweathermap.org/img/wn/" + icon + "@2x.png";

            const weatherDescString = "<p>" + "Weather description is " + description + "</p>";
            const temperatureString = "<h1>The temperature in " + query + " is "+ temp + " Fahrenheit </h1>";
            res.write(temperatureString);
            res.write(weatherDescString);
            res.write("<img src=" + "\"" + imageURL + "\"" + ">");
            res.send();
        });

    });

});



app.listen(3000, function () {
    console.log("Server running on port 3000");
});

References

The Complete 2020 Web Development BootCamp. Udemy

Comments

Popular posts from this blog

QTreeView and QTableView dynamic changes

C++ Tour Part III

C++ strings and string_view