Find Prices and compare using RAPID API in JAVA

Photo by Sajad Nori on Unsplash

Find Prices and compare using RAPID API in JAVA

Java の RAPIDAPI で価格チャートを比較 @hustler

·

4 min read

problem :

問題 :

Every time I go shopping my eyes would stay wide open!! why?

yes, you guessed it right because of the high prices of things in japan. especially coming from a country like India this is really shocking. on initial days I used to compare prices for example

1kg of banana would cost around 90¥(~₹60) in India while in japan it is ~400¥(~₹250).

well one can argue comparing prices won’t reduce the expansivity in japan.

thats true,but my stupid brain doesn’t understand that🥴

so I thought why not bulid something which could give me information about the general expenses of things across various countries.

買い物に行くたびに、目を大きく見開いていました!!

はい、日本の物価が高いので、あなたはそれを正しく推測しました. 特にインドのような国から来て、これは本当に衝撃的です. たとえば、最初の日に価格を比較していました

1kg のバナナは、インドでは約 90 円 (~ ₹60) ですが、日本では ~ 400 円 (~ ₹250) です。

価格を比較しても、日本での拡張性が低下することはないと主張できます。

それは本当ですが、私の愚かな脳はそれを理解していません🥴

そこで、さまざまな国での一般的な費用に関する情報を提供できるものを作成してみませんか。

solution:

解決:

while hunting for the solution I came across this API called RAPIDAPI which gives you access to all the information called as Cost of living and prices API they also have various other API.

you can check out here-https://rapidapi.com/hub

I have built a non-GUI-based(sorry for hurting your eyes🥺) java application.

note: the final application is like a tourist app who wants information about places near kyoto,but this blog covers only a part of it.

解決策を探しているときに、RAPIDAPI と呼ばれるこの API に出会いました。これにより、生活費と価格 API と呼ばれるすべての情報にアクセスできます。これらには、他のさまざまな API もあります。

ここで確認できます - https://rapidapi.com/hub

非 GUI ベースの (見辛くてごめんなさい🥺) Java アプリケーションを作成しました。

注: 最終的なアプリケーションは、京都近郊の場所の情報を求める観光アプリのようなものですが、このブログではその一部のみを取り上げます。

this is the main function which is fetching the data from the API

  • It consits of three steps

    • step-1 first asking user for the country and city and storing it in a variable called fcountry & fcity

    • step-2 using try and catch method make a get request to the API.make use of the stored variables from step-1

      note: the endpoint code is available in their website in various languages.

    • step-3 convert response to json object

      once you have JSON data iterate over it and display it.

  • これは、API からデータをフェッチするメイン関数です。

  • 3つのステップで構成されています

    • ステップ 1 最初にユーザーに国と都市を尋ね、それを fcountry & fcity という変数に格納します

    • ステップ2: try-catch 文を使用して API に向けて GET リクエストを作成します。ス

    • ステップ 3 レスポンスを json オブジェクトに変換

      JSONデータを取得したら、それを繰り返し処理して表示します。

public void getDetailsfromAPI() {

     //getting input from user of desired country and city
     Scanner sc = new Scanner(System.in);
     System.out.println("choose country");
     String fcountry = sc.nextLine();
     fcountry = fcountry.replace(" ", "%20");
     System.out.println("choose city");
     String fcity = sc.nextLine();
     fcity =fcity.replace(" ", "%20");

     try {
            //firing the get request from RAPID API
         HttpResponse<JsonNode> response = Unirest.get("<https://cost-of-living-and-prices.p.rapidapi.com/prices?city_name="+fcity+"&country_name="+fcountry+">")
             .header("X-RapidAPI-Key", "XXXXXXXXXXXXXXXXXXXXXXX")
             .header("X-RapidAPI-Host", "cost-of-living-and-prices.p.rapidapi.com")
             .queryString("parameter", "value")
             .asJson();

            // converting response in to JSON object
            JsonNode ret = response.getBody();
            JSONObject obj = ret.getObject();

                        //looping over the JSON object using Iterators in java
            Iterator<Object> iterator = obj.getJSONArray("prices").iterator();
            org.json.JSONObject data = (JSONObject) iterator.next();

            System.out.println("Country Name :" +obj.getString("country_name"));
            System.out.println("City Name :" + obj.getString("city_name"));
            System.out.println("Currency Code :" + data.get("currency_code"));
            System.out.println("---------------------------------------------------------------------------------------------");
            System.out.println("Price of Daily food Items");
            dailyItems(obj);
            System.out.println("---------------------------------------------------------------------------------------------");
            System.out.println("Cost of Transportation");
            transportation(obj);
            System.out.println("---------------------------------------------------------------------------------------------");
            System.out.println("Utilities Per Month");
            utilities(obj);
            System.out.println("---------------------------------------------------------------------------------------------");
            System.out.println("price of Restaurants");
            restaurant(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

This is the output screen

  • also if you notice functions like dailyItems(JSONObject obj),transportation(JSONObject obj),utilities(JSONObject obj),restaurant(JSONObject obj)

    • These are just functions for getting specific data. if the "category_name" string is

    • if string = "Markets" it will fetch daily need items.

    • if string = ‘Transportation’.it will fetch transport expenses.

    • if string = ‘"Utilities Per Month"’.it will fetch utilites expenses.

    • if string =‘Restaurants"’.it will fetch prices of items in a restaurant

  • また、「dailyItems(JSONObject obj),transportation(JSONObject obj),utilities(JSONObject obj),restaurant(JSONObject obj)などの関数に気付いた場合

    • これらは、特定のデータを取得するための単なる関数です。 "category_name" 文字列が..

    • string = "Markets" の場合、毎日必要なアイテムを取得します。

    • string = ‘Transportation’ の場合、交通費を取得します。

    • string = ‘"Utilities Per Month"’ の場合、光熱費が取得されます。

    • string =‘Restaurants"’ の場合、レストランの商品の価格を取得します

```java
public static void dailyItems(JSONObject obj){

    Iterator<Object> iterator = obj.getJSONArray("prices").iterator();

    int count = 0;
    while (iterator.hasNext()) {
        org.json.JSONObject data1 = (JSONObject) iterator.next();
        String str = (String) data1.get("category_name");

        if (str.equalsIgnoreCase("Markets")) {
            count++;
            if (count == 5) {
                break;
            }
            System.out.println("Item:" + data1.get("item_name") + "\\tAverage Price:" + data1.get("avg"));
        }
    }
}
```

here is small demo of overall C-R-D application.

これは、C-R-D アプリケーション全体の小さなデモです。

note: if you want to run appplication there are many jar file that need to be used as show in picture in left.

注: アプリケーションを実行する場合は、左の図のように使用する必要がある多くの jar ファイルがあります。

link to code - https://github.com/Sharanya98/TouristManagmnet-RapidAPI/tree/master

“If you work on something a little bit every day, you end up with something that is massive.” —Kenneth Goldsmith

Stay healthy,Keep Hustling!!❤️