Find an API and implement Fetch following Covid example. Answer these questions in implementation…

Benefit of using and API? Benefit(s) of backend implementation?

To Do:

  • [x] find API on rapidAPI
  • [x] copy/repackage code from project link
  • [x] make sure that httprequest itself works
  • [x] parse json to find stuff
  • [ ] possibly build spring boot around it (using objects);
  • [ ] restart instance, test on ec2 --> deploy
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

//RapidAPI header  https://rapidapi.com/spamakashrajtech/api/corona-virus-world-and-india-data
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://weatherapi-com.p.rapidapi.com/current.json?q=209.66.205.197"))
    .header("X-RapidAPI-Key", "0fb4bb4059msh8489d467f79e14ep1d57f9jsnd0d67fb163e6")
    .header("X-RapidAPI-Host", "weatherapi-com.p.rapidapi.com")
    .method("GET", HttpRequest.BodyPublishers.noBody())
    .build();

//RapidAPI request and response
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

//RapidAPI Body
System.out.println(response.body());
{"location":{"name":"Rancho Penasquitos","region":"California","country":"United States of America","lat":32.96,"lon":-117.11,"tz_id":"America/Los_Angeles","localtime_epoch":1664390698,"localtime":"2022-09-28 11:44"},"current":{"last_updated_epoch":1664389800,"last_updated":"2022-09-28 11:30","temp_c":28.3,"temp_f":82.9,"is_day":1,"condition":{"text":"Sunny","icon":"//cdn.weatherapi.com/weather/64x64/day/113.png","code":1000},"wind_mph":2.2,"wind_kph":3.6,"wind_degree":239,"wind_dir":"WSW","pressure_mb":1014.0,"pressure_in":29.95,"precip_mm":0.0,"precip_in":0.0,"humidity":55,"cloud":0,"feelslike_c":29.6,"feelslike_f":85.3,"vis_km":16.0,"vis_miles":9.0,"uv":7.0,"gust_mph":4.3,"gust_kph":6.8}}

Backend implementation on Spring boot:

backend API

As seen, I set up the code such that I could get (curl) a site on my local spring boot, returning the data about weather. I was about to implement this into displaying with javascript, but as of now the AWS servers are down so the links are not working yet. If it does get fixed, it will be seen here.

The source code can be seen here, but here is a snippet of the code that i changed:

public ResponseEntity<JSONObject> getCovid() {

        //calls API once a day, sets body and status properties
        Long currentTime = System.currentTimeMillis()/(1000*60);
        if (last_run == null || (currentTime - last_run)>5)
        {
            try {  //APIs can fail (ie Internet or Service down)

                //RapidAPI header
                HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://weatherapi-com.p.rapidapi.com/current.json?q=209.66.205.197"))
                    .header("X-RapidAPI-Key", "0fb4bb4059msh8489d467f79e14ep1d57f9jsnd0d67fb163e6")
                    .header("X-RapidAPI-Host", "weatherapi-com.p.rapidapi.com")
                    .method("GET", HttpRequest.BodyPublishers.noBody())
                    .build();


                //RapidAPI request and response
                HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

                //JSONParser extracts text body and parses to JSONObject
                this.body = (JSONObject) new JSONParser().parse(response.body());
                this.status = HttpStatus.OK;  //200 success
                this.last_run = currentTime;
            }
            catch (Exception e) {  //capture failure info
                HashMap<String, String> status = new HashMap<>();
                status.put("status", "RapidApi failure: " + e);

                //Setup object for error
                this.body = (JSONObject) status;
                this.status = HttpStatus.INTERNAL_SERVER_ERROR; //500 error
                this.last_run = null;
            }
        }

Instead of getting the date, I get the epoch time and convert it to minutes. When I pull from the API, if it is successfull, I set the time that I ran the API to the last_run. So, if the difference between the two runs is greater than 5 minutes, then it will request the API again. As this is weather, I think 5 minutes is adequate time, and also enough to take advantage of my 1 million requests per month.

Questions?

  1. Benefit of using an API?

An API allows code to interact with data from a server, and this is necessary especailly for our development environment, which is deploying a website. We will constantly have to interact with web servers and possibly serve our own data, so an API is necessary to make it easy to access data without having to write a lot of code. It provides a template for easier interaction in the future.

  1. Benefits of backend implementation?

As described above, if it was only frontend, the code would have to request the source api every time a user reloads, which could be wasteful if the API hasn't had any meaningful changes or updates to its data. So, mine limits requests to every 5 minutes to the source server, caching and saving the last run. This cuts down on unnecessary cost, which could be a problem when scaled up.