Using Rest APIs for Client-Server Interactions

written by Raviteja Lingineni

Whenever you build a program, there are two sides to the interaction model. Once is the front-end and the other is back-end. The front-end is the code and the UI that is associated with what the user sees, and the back-end is where all the data is stored and saved. In order to build a larger application that goes beyond just your computer, both components are necessary. However, the question becomes, how does the client interact with the server?

image

Prerequisites

Here are the things you would want to install beforehand:

Postman - Allows you to visualize and see Web requests

WeatherMap - Sign-up and get your own API Token

Eclipse - Or a similar IDE, we will use some basic JAVA

Jumping to it

After you have installed Postman, let's understand how the client-server model works. The idea is that the client recieves data from the server.

You know your browser right, Chrome, Safari, Internet Explorer (don't use IE), it's also a client application. Whenever you go to a website, the server of that website gives back HTML.

The type of Web Request that happens when you type your url into the address bar is known as a GET Request.

GET Requests

  1. Open Postman
  2. In the address bar type www.google.com
  3. Using the dropdown to the left, change it to GET
  4. Click on Send

The response you see is for the Google Homepage. Just like how you made a request from Postman, your browser does the same thing, and the HTML it recieves is rendered for you to make the webpage you see.

Practice with this JSON PLACEHOLDER

JSON

Now of course, you aren't going to send and pass data using HTML. That's only a markup language for your web browser to see.

Therefore, we use JSON to make our requests and organize information. It's just a way of formatting information. Here is a sample pertaining to an object:

{
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
    "id": {
        "description": "The unique identifier for a product",
        "type": "integer"
    }
},
"required": ["id"]
}

Open the above code in an understandable editor. Pasting the code in the editor will allow you to understand how the data is formatted.

Makes sense? Objects use curly braces, and you can nest objects within each other, and also make arrays using square braces.

Getting Weather Data

Good, now let's fetch weather data. The server contains data for weather in different places. We need to make a request and show that data.

Here is how we will do this:

1. Test our Web Request
  • You should have your Weather Map token by now
  • Read the instructions here on how to make calls to the API. All APIs have some docs that say how to use it.

Here is a sample call:

 api.openweathermap.org/data/2.5/forecast/weather?q=Dallas&APPID=TOKEN          

Make a GET request using Postman. You should see some data like this:

{
      "coord": {
    "lon": -0.13,
        "lat": 51.51
      }
      ...
}

This is the weather related data that is contained in the response pertaining to your request. Understand these values by reading the docs.

Now we have to make this same request using a language. Postman only showed us it is possible.

Using Java to Send Web Requests

Java can be used to parse our JSON and do something. For example, say we want to make a nice UI app that shows us the weather, how can we do so?

Well, first of all, that request we made from Postman, we need to do it from our Java program. Here is how we can do that:

static String startWebRequest() throws IOException
{
    String weatherURL = "http://api.openweathermap.org/data/2.5/weather?q=CITY&APPID=26aa1d90a24c98fad4beaac70ddbf274";             //        please get your own token to use from API.Openweathermap

      StringBuilder result = new StringBuilder(); //this is going to hold the JSON Response from the server
      URL url = new URL(weatherURL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
         result.append(line);
      }
      rd.close();
      System.out.println(result.toString());

      return result.toString();
   }

This method will allow us to see the results of the GET Web Request just like Postman

Using Java to Parse Web Requests

Now we will use GSON to parse Web Requests. GSON is a library to parse JSON in Java. Get it from here. Then you will need to add it to your IDE.

Follow the instructions here for Eclipse. You can google for more information as well.

To Parse in GSON, it is is fairly easy. First, after you understand your JSON, use it to parse in this way. Here is a method that takes in a JSON string. We break up each of the curly braces into smaller objects and then narrow down to a smaller value. In this case, we want the longitude of a city from the weather response

static double parseJson(String json) //json is a string of json, we get this from making our request
{
    JsonElement jelement = new JsonParser().parse(json); //you will parse it first into a JSONElement
    JsonObject  MasterWeatherObject = jelement.getAsJsonObject();  //You will then take that jelement, and then break it down into a json object. Use the JSONEDITORONLINE website, basically, you are trying narrow down to whatever you want

    JsonObject  coordinateObject = MasterWeatherObject.getAsJsonObject("coord"); //we will get the coordinate object
    double  longitude = coordinateObject.get("lon").getAsDouble(); //now we will narrow down to get the value of the longitute
    return longitude;  //return our longitude

}

Once you have the value you want, just build up a nice looking UI and that's it! You have successfully learned Client-Server Interaction. We took data from the server and showed it on the client.

If you ever want to work with Twitter Data, it works the same way. REST APIS are the way data exchange happens over the web. Hopefully, that made sense. It's a lot to take in, but you're on your way to making bigger and better applications.