Home > Software engineering >  How can I get specific data from a REST API in?
How can I get specific data from a REST API in?

Time:01-13

So I'm trying to access data frim a rest api using java code and I'm not very experienced in getting data from an api using java. I had found the code below on another question. This code was able to output all the data from the link but I'm a bit confused on how to get specific values from the link. The link in the code below shows the nutrition info for an apple and what I'm looking for is being able to output specific values such as the fdcId or the description.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
    public static void main(String[] args) {
        try {

            URL url = new URL("https://api.nal.usda.gov/fdc/v1/food/1750339?api_key=DEMO_KEY");//your url i.e fetch data from .
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                          conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- "   e);
        }
    }
}

I haven't really tried much with the code. I tried looking for the answer for this online and didn't find much

CodePudding user response:

You need to look how to parse Json in Java. This way you can take any data you need from that Json file. Some explanations for the similar question are here.

CodePudding user response:

Usually Spring or other frameworks used for this purposes. In your example you can save JSON response to string like this:

String reponse = "";
String line;
while ((line = br.readLine()) != null) {
    reponse  = line;
}

And than parse this JSON, f.e. using Jackson ObjectMapper convert it into your dto.
There is an example here: https://www.baeldung.com/jackson-object-mapper-tutorial

CodePudding user response:

Your question should be divided in two parts:

  1. How to read info from API
  2. How to parse it.

The first part you already did. But you can do it with less code by far. You can use 3d party HTTP clients. The most popular are Apache Http Client with good tutorial - Apache HttpClient Tutorial and OK Http client with good tutorial - A Guide to OkHttp. However, I wrote my own Http client that is not widely known but very simple to use.

The second part is how to parse Json. And for that you can use also 3d party Json parsers. The most popular ones would be Json Jackson or Gson (of Google). And again I also wrote my own thin wrapper over Json-Jackson that allows you to parse Json very simply. Here is the code example that uses my own utilities:

HttpClient httpClient = new HttpClient();
try {
    httpClient.setConnectionUrl("https://api.nal.usda.gov/fdc/v1/food/1750339?api_key=DEMO_KEY");
    httpClient.setRequestHeader("Accept", "application/json");
    String jsonResponse = httpClient.sendHttpRequest(HttpClient.HttpMethod.GET);
    Map<String, Object> map = JsonUtils.readObjectFromJsonString(jsonResponse, Map.class);
    System.out.println("fdcid: "   map.get("fdcId"));
    System.out.println("description: "   map.get("description"));
} catch (Exception e) {
    System.out.println(httpClient.getLastResponseCode()   " "
              httpClient.getLastResponseMessage()   TextUtils.getStacktrace(e, false));
}

If you run this code this would be the output:

fdcid: 1750339
description: Apples, red delicious, with skin, raw

The classes HttpClient, JsonUtils and TextUtils all come as part of MgntUtils Open Source library written and maintained by me. Here is Javadoc for the library If you want the source code of the whole library you can get it on Github here, and just the library as Maven artifact is available from Maven Central here

  • Related