Tomorrow.io's Resilience Platform is Here. Learn More.

X

How to Use a City-Name Based Weather API in Java?

Integrate accurate, real-time weather data into your Java application by using a city-name based weather API from Tomorrow.io

Filip Dimkovski
By Filip Dimkovski
Janet Barben Bio
Edited by Janet Barben

Updated February 4, 2024.

Integrating accurate weather data into applications can significantly enhance their functionality and user experience. This is especially true for applications that require location-specific weather information, such as travel planners, event organizers, and agricultural apps.

Typically, one of the most user-friendly methods of retrieving weather data is using a city-name-based Java weather API with Tomorrow.io. In this article, we'll go through the process of using a Java weather API and fetching the data via the city name.



Getting an API Key

To start using the weather API by city name, you first need to get an API key. So, visit the sign-up page at Tomorrow.io and fill in your basic account information. Then, visit the API Management section, where you can find your API Key as shown in the screenshot below:

API Management Tomorrow.io


Setting up Your Java Environment

In your Java application, you'll use the `OkHttpClient` library to make a network request to the weather API. Include the OkHttp dependency in your project's build file (`pom.xml` for Maven builds or `build.gradle` for Gradle builds). Then, you use the `OkHttpClient` to send a request to the weather API, as shown in the code snippet below:

package org.example;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://api.tomorrow.io/v4/weather/realtime?location=toronto&apikey=YOUR_API_KEY")
                .get()
                .addHeader("accept", "application/json")
                .build();

        try {
            Response response = client.newCall(request).execute();
	    if (response.isSuccessful() && response.body() != null) {
                String responseData = response.body().string();
                System.out.println(responseData);
            } else {
                System.out.println("Request not successful: " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code snippet builds a GET request with the specified URL, sending a request to fetch real-time weather data for Toronto. Of course, you must replace 'toronto' with the appropriate city name and replace your API key where the YOUR_API_KEY placeholder stands. The response will contain an object with the weather data returned by the API, which you can then process and integrate into your application as needed.

Analyzing the Response

Let's take a look at the response:

{
  "data": {
    "time": "2024-01-19T16:20:00Z",
    "values": {
      "cloudBase": 0.66,
      "cloudCeiling": 0.66,
      "cloudCover": 100,
      "dewPoint": -12.63,
      "freezingRainIntensity": 0,
      "humidity": 65,
      "precipitationProbability": 0,
      "pressureSurfaceLevel": 1005.93,
      "rainIntensity": 0,
      "sleetIntensity": 0,
      "snowIntensity": 0,
      "temperature": -6.81,
      "temperatureApparent": -13.67,
      "uvHealthConcern": 0,
      "uvIndex": 0,
      "visibility": 15.33,
      "weatherCode": 1001,
      "windDirection": 354.88,
      "windGust": 8.38,
      "windSpeed": 5.31
    }
  },
  "location": {
    "lat": 43.653480529785156,
    "lon": -79.3839340209961,
    "name": "Toronto, Golden Horseshoe, Ontario, Canada",
    "type": "administrative"
  }
}
As we can see, the response is in a JSON format, offering a rich and detailed representation of the current weather conditions in the city for which we fetched information—Toronto, Canada.

Summary

All in all, using a weather API by city name is a powerful and efficient way to access and utilize real-time weather data. This article demonstrates everything you need to know, from setting up your Java environment to handling the JSON response. Whether for personal use or businesses in sectors such as agriculture and transportation, using a Java weather API by city name opens up numerous possibilities.