Popular Searches
Popular Course Categories
Popular Courses

Developing a Weather App Using REST API Integration

Developing a Weather App Using REST API Integration

Real-World Android Application Projects

Developing a Weather App Using REST API Integration

Course: Android App Development

Topic: Developing a Weather App Using REST API Integration

Course Link: Android App Development Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Weather App Development

A Weather App is an Android application that displays current weather conditions and forecast information for a selected location. It retrieves weather data from an online service through a REST API and presents the information in a user-friendly interface.

Unlike an application that displays hardcoded weather information, a REST API-based weather app requests data from a remote server and updates the interface with the returned response. Users can search for cities, view temperature and humidity, check wind speed, and explore weather forecasts.

This project introduces important Android development concepts, including HTTP requests, JSON parsing, asynchronous programming, API integration, error handling, location services, and responsive UI design.

Key Features

  • Display current weather conditions.
  • Search weather by city name.
  • Show temperature, humidity, and wind speed.
  • Display weather descriptions and icons.
  • Show minimum and maximum temperatures.
  • Retrieve forecasts for upcoming days.
  • Allow users to view weather for their current location, with permission.
  • Handle network errors and invalid city names.
  • Show loading indicators while retrieving data.
  • Optionally save recent searches and favorite cities.

2. Learning Objectives

After completing this project, learners should be able to:

  • Understand REST API concepts and HTTP communication.
  • Create an Android application using Kotlin or Java.
  • Send HTTP requests to a weather service.
  • Parse JSON responses into application data models.
  • Use asynchronous programming to avoid blocking the UI thread.
  • Display API data in Android UI components.
  • Handle loading, success, empty, and error states.
  • Implement city search and location-based weather retrieval.
  • Manage API keys and network permissions appropriately.
  • Test and debug an API-integrated application.

3. Technologies and Tools Required

Technology Purpose
Android Studio IDE for developing and debugging the application.
Kotlin or Java Implements application logic and API communication.
XML Layouts Creates the interface when using the Android Views system.
Jetpack Compose Alternative toolkit for building Android interfaces.
REST API Provides weather data from a remote service.
Retrofit HTTP client for defining and calling API endpoints.
OkHttp Handles HTTP communication and related networking features.
JSON Data format commonly used for API responses.
Gson or Kotlin Serialization Converts JSON data into Kotlin or Java objects.
Coroutines Supports asynchronous network requests in Kotlin.
Location Services (Optional) Helps retrieve a user's location when permission is granted.

For this project, Kotlin, Retrofit, coroutines, and a JSON serialization library provide a practical implementation approach. Java and other networking libraries can also be used.

4. Understanding REST API Integration

REST stands for Representational State Transfer. A REST API exposes resources through HTTP endpoints so that applications can request or submit data.

A weather app typically sends an HTTP GET request containing a city name or geographic coordinates. The server processes the request and returns weather information in JSON format.

4.1 Example API Request

A weather provider may offer an endpoint with a structure similar to the following:

GET https://api.example.com/weather?city=Mumbai&key=YOUR_API_KEY

This is an illustrative URL, not a working weather endpoint. Replace the domain, parameters, and authentication method with those documented by the weather provider you select.

4.2 Example JSON Response

{
  "city": "Mumbai",
  "temperature": 29.5,
  "humidity": 74,
  "wind_speed": 12.3,
  "description": "Partly cloudy"
}

The response above is illustrative. Actual field names, units, and JSON structure vary by provider and endpoint.

4.3 How the Integration Works

  1. The user opens the weather application.
  2. The user enters a city or selects the current-location option.
  3. The application validates the input.
  4. The networking layer sends a request to the weather API.
  5. The API server processes the request.
  6. The server returns a response, typically in JSON format.
  7. The application converts the response into a data model.
  8. The ViewModel updates the UI state.
  9. The interface displays the weather information or an appropriate error.

5. Selecting a Weather API Provider

Before implementation, select a weather provider that offers the required current-weather and forecast endpoints.

Common Evaluation Criteria

  • Availability of current-weather data.
  • Forecast availability and forecast duration.
  • API key and authentication requirements.
  • Request quotas and rate limits.
  • Supported locations and geographic coverage.
  • Available temperature and wind-speed units.
  • Response format and documentation quality.
  • Pricing, licensing, and attribution requirements.

Read the provider's documentation carefully. Some services require a city identifier or geographic coordinates rather than a city name, and some separate geocoding, current-weather, and forecast endpoints.

6. Planning the Application Screens

Screen Description
Home Screen Displays the selected city's current weather conditions.
City Search Screen Allows users to search for a city or location.
Forecast Screen Displays upcoming weather conditions.
Favorite Cities Screen Provides quick access to saved locations.
Settings Screen Allows users to select units and other preferences.
Error and Empty States Explains network problems, invalid searches, and unavailable data.

7. Creating the Android Project

  1. Open Android Studio.
  2. Select New Project.
  3. Choose a suitable starter template.
  4. Enter the project name as WeatherApp.
  5. Select Kotlin or Java.
  6. Configure the package name and minimum Android version.
  7. Allow Gradle to synchronize the project.
  8. Run the starter application on an emulator or physical device.
  9. Confirm that the project runs successfully before adding networking code.

8. Configuring Internet Permission

An Android application needs network access permission to make weather API requests. Add the following permission to the application's manifest, outside the application element:

<uses-permission
    android:name="android.permission.INTERNET" />

If the app uses the user's current location, it will also need the appropriate location permissions and a permission-request flow. Internet access permission itself does not require a runtime permission prompt.

9. Adding Networking Dependencies

Retrofit simplifies HTTP requests by allowing API endpoints to be declared as Kotlin interfaces. Add compatible Retrofit, converter, and coroutine dependencies to the module-level Gradle file.

dependencies {
    implementation("com.squareup.retrofit2:retrofit:RETROFIT_VERSION")
    implementation("com.squareup.retrofit2:converter-gson:RETROFIT_VERSION")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:COROUTINES_VERSION")
}

Replace the version placeholders with compatible stable versions from the official project documentation. Keep related Retrofit artifacts on matching versions.

10. Creating the Weather Data Model

A data model represents the weather information returned by the API. Its fields must match the actual response schema or be mapped appropriately by the serialization library.

For the illustrative JSON response in this lesson, a Kotlin model could be written as follows:

data class WeatherResponse(
    val city: String,
    val temperature: Double,
    val humidity: Int,
    val wind_speed: Double,
    val description: String
)

This model is only suitable for the sample JSON structure shown earlier. For a real provider, inspect its response and define nested data classes or serialization annotations where required.

11. Defining the Weather API Interface

Retrofit uses an interface to describe the HTTP endpoints that the application will call. The following example represents a hypothetical provider returning the sample weather model.

import retrofit2.http.GET
import retrofit2.http.Query

interface WeatherApiService {

    @GET("weather")
    suspend fun getCurrentWeather(
        @Query("city") city: String,
        @Query("key") apiKey: String
    ): WeatherResponse
}

The endpoint path and parameter names must match the selected provider's documentation. If the provider uses latitude and longitude, different parameters and possibly a separate endpoint will be required.

12. Creating the Retrofit Client

The Retrofit client configures the base URL and JSON converter used by the networking layer.

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClient {

    private const val BASE_URL =
        "https://api.example.com/"

    val weatherApi: WeatherApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(
                GsonConverterFactory.create()
            )
            .build()
            .create(WeatherApiService::class.java)
    }
}

Replace the example base URL with the provider's documented HTTPS base URL. Retrofit requires a valid base URL ending in a slash. This example does not include authentication configuration beyond the illustrative API-key query parameter.

13. Managing API Keys Securely

Many weather services require an API key to authenticate requests and apply usage limits.

Recommended Practices

  • Do not commit real API keys to a public source repository.
  • Do not display API keys in the user interface or logs.
  • Use local development configuration for keys during development.
  • Restrict keys through provider-supported controls when available.
  • Monitor request quotas and unexpected usage.
  • For production applications, consider routing requests through a backend that keeps privileged credentials server-side.

Build configuration can help avoid accidentally committing a key, but a key embedded in a distributed Android application may still be extracted. Use a backend when the credential must remain confidential.

14. Fetching Weather Data Asynchronously

Network requests should not run on the main UI thread because network delays can make the application unresponsive. Retrofit suspend functions can be called from Kotlin coroutines.

suspend fun fetchWeather(
    city: String
): WeatherResponse {
    return RetrofitClient.weatherApi
        .getCurrentWeather(
            city = city,
            apiKey = BuildConfig.WEATHER_API_KEY
        )
}

This function assumes the API key is configured in the build configuration and the API interface matches the provider. It should be called from a coroutine scope managed by the ViewModel or another suitable lifecycle-aware component.

15. Creating the Repository Layer

A repository separates data retrieval from UI components. It provides a single place to handle API calls, response mapping, and data-related errors.

class WeatherRepository(
    private val api: WeatherApiService,
    private val apiKey: String
) {
    suspend fun getWeather(
        city: String
    ): WeatherResponse {
        require(city.isNotBlank()) {
            "City name is required"
        }

        return api.getCurrentWeather(
            city = city.trim(),
            apiKey = apiKey
        )
    }
}

In a complete implementation, map the raw API response to a UI model and handle HTTP errors, timeouts, parsing failures, and connectivity problems explicitly.

16. Managing UI State with a ViewModel

The ViewModel manages loading, successful results, and error states. This prevents networking logic from becoming tightly coupled to an Activity or composable screen.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class WeatherViewModel(
    private val repository: WeatherRepository
) : ViewModel() {

    var weather: WeatherResponse? = null
        private set

    var isLoading: Boolean = false
        private set

    var errorMessage: String? = null
        private set

    fun loadWeather(city: String) {
        if (city.isBlank()) {
            errorMessage = "Enter a city name"
            return
        }

        viewModelScope.launch {
            isLoading = true
            errorMessage = null

            try {
                weather = repository.getWeather(city)
            } catch (e: Exception) {
                errorMessage =
                    "Unable to load weather. Please try again."
            } finally {
                isLoading = false
            }
        }
    }
}

This example demonstrates the general flow, but plain mutable properties do not automatically notify the UI when they change. A production implementation should expose observable state using StateFlow, LiveData, or Compose's state mechanisms. Handle coroutine cancellation appropriately and avoid catching cancellation as an ordinary error.

17. Designing the Weather Home Screen

The home screen should show the most important weather information clearly without overwhelming the user.

Recommended UI Elements

  • City name and country, where available.
  • Current temperature and unit.
  • Weather condition description.
  • Weather icon.
  • Feels-like temperature.
  • Humidity percentage.
  • Wind speed and direction, if available.
  • Minimum and maximum temperature, when supplied.
  • Last-updated time.
  • Search field and refresh action.

Use cards or clearly grouped sections to organize information. Ensure that temperature units and other measurements are displayed consistently.

18. Implementing City Search

City search allows users to retrieve weather information for different locations.

Implementation Steps

  1. Add a text input for the city name.
  2. Add a Search button or submit action on the keyboard.
  3. Trim whitespace and validate the input.
  4. Send the city name to the repository.
  5. Display a loading indicator while the request is running.
  6. Show the returned weather information when successful.
  7. Display a helpful message if the city cannot be found.

Some providers return several places with similar names. For better accuracy, use a geocoding endpoint to let users select a specific city and country before retrieving its weather.

19. Parsing and Displaying JSON Responses

JSON is a text-based format for exchanging structured data. Retrofit converters can automatically map JSON responses to data classes when their field names and types match the response schema.

Example JSON

{
  "city": "Pune",
  "temperature": 27.0,
  "humidity": 62,
  "wind_speed": 8.4,
  "description": "Clear sky"
}

Displaying the Parsed Values

val temperatureText =
    "${weather.temperature} °C"

val humidityText =
    "Humidity: ${weather.humidity}%"

val windText =
    "Wind speed: ${weather.wind_speed}"

val descriptionText =
    weather.description

Use the actual units returned by the API or request a specific unit system supported by the provider. Do not assume that every API returns Celsius, kilometers per hour, or the same JSON field names.

20. Adding Weather Icons and Visual Indicators

Weather icons help users understand conditions quickly. The application can use local drawable resources or icons supplied by the weather provider.

  • Sunny conditions can use a sun icon.
  • Cloudy conditions can use a cloud icon.
  • Rainy conditions can use a rain icon.
  • Thunderstorms can use a lightning or storm icon.
  • Snowy conditions can use a snow icon.
  • Foggy conditions can use a fog icon.

Use the provider's documented condition codes or icon mapping rather than relying entirely on a text description. If remote icon URLs are used, load images asynchronously and provide a fallback when an image fails to load.

21. Displaying Weather Forecasts

A forecast screen provides information about expected weather conditions in the coming hours or days. Forecast data normally comes from a separate API endpoint or a specific forecast section of the provider's response.

Possible Forecast Features

  • Hourly temperature forecast.
  • Daily minimum and maximum temperatures.
  • Expected weather conditions.
  • Rain or precipitation probability when available.
  • Wind speed and humidity forecasts when supported.

Display forecast timestamps using the appropriate location's time zone. Explain the forecast period and avoid presenting forecast estimates as guaranteed conditions.

22. Integrating Current Location

Current-location weather allows users to retrieve conditions for their approximate geographic position without entering a city manually.

Implementation Workflow

  1. Explain why location access is useful.
  2. Request the appropriate Android location permission.
  3. Check whether permission has been granted.
  4. Retrieve the location using a suitable location provider.
  5. Send latitude and longitude to a weather endpoint or resolve them through geocoding.
  6. Display weather data for the resolved location.
  7. Provide a city-search alternative if permission is denied.

Request only the level of location access required for the feature. A weather app generally does not need continuous background location tracking. Handle unavailable GPS, disabled location services, and denied permissions gracefully.

23. Handling Network and API Errors

Network requests may fail for many reasons. A robust weather app should explain problems clearly and provide a useful next step.

Error Possible Cause Recommended Handling
No Internet connection The device is offline. Show a connectivity message and allow retrying.
HTTP 401 or 403 Invalid credentials or insufficient access. Check API configuration and provider permissions.
HTTP 404 Unknown city or endpoint. Check the search term and endpoint path.
HTTP 429 Request quota or rate limit exceeded. Respect the provider's rate-limit guidance.
HTTP 5xx Remote server failure. Show a temporary error and offer retry.
JSON parsing error Unexpected response structure. Validate the response model and inspect safe diagnostic logs.
Request timeout Slow connection or server response. Configure suitable timeouts and offer retry.
Invalid location Unknown or ambiguous city name. Suggest a different spelling or location selection.

24. Implementing Loading and Error States

The interface should communicate what the application is doing during a request.

  • Loading: Display a progress indicator while retrieving data.
  • Success: Display current weather and forecast information.
  • Error: Show a readable message and a retry option.
  • Empty: Explain that no weather data is available for the selected location.
  • Offline: If cached weather exists, display it with a clear last-updated time.

Do not leave the screen blank or show a success message before the API request has completed successfully.

25. Caching Weather Data

Caching stores previously retrieved information so it can be displayed quickly and may remain available when the network is unavailable.

Benefits of Caching

  • Reduces repeated API requests.
  • Improves the perceived loading speed.
  • Can provide a fallback during temporary connectivity problems.
  • Helps reduce unnecessary use of provider quotas.

Use an appropriate local storage solution, such as Room or DataStore depending on the data structure. Store a timestamp with cached weather and clearly indicate when information was last updated. Weather data can become outdated quickly, so caching must follow the provider's terms and the application's freshness requirements.

26. Managing API Rate Limits and Performance

Weather providers often impose request limits. The app should avoid sending unnecessary requests when users type or refresh repeatedly.

  • Debounce city-search input when requests are triggered while typing.
  • Cancel outdated requests when a newer search replaces them.
  • Cache suitable responses.
  • Avoid repeatedly requesting the same forecast without a reason.
  • Use reasonable connection and read timeouts.
  • Handle rate-limit responses according to the provider's documentation.
  • Keep network operations off the main thread.
  • Display loading states without unnecessarily blocking the entire interface.

27. Testing the Weather App

Testing helps ensure that the application retrieves and displays weather information correctly under normal and failure conditions.

27.1 Functional Testing

  • Search for a valid city.
  • Search for an invalid city.
  • Verify displayed temperature and humidity.
  • Check that weather icons match the returned conditions.
  • Test forecast navigation.
  • Test the current-location feature if implemented.
  • Verify that refreshing the screen retrieves updated data.

27.2 Network Testing

  • Test with the device offline.
  • Simulate a slow network.
  • Test authentication errors and rate limits where practical.
  • Verify that malformed or unexpected responses do not crash the app.
  • Check retry behavior after temporary failures.

27.3 UI Testing

  • Verify layout on different screen sizes.
  • Check text readability and unit labels.
  • Confirm that the loading indicator disappears after a request.
  • Verify that error messages are understandable.
  • Test keyboard submission and city-search behavior.

Sample Test Cases

Test Case Action Expected Result
TC01 Search for a valid city. Weather data for the selected location is displayed.
TC02 Search using an empty field. A validation message appears.
TC03 Search for a nonexistent city. A location error is displayed.
TC04 Disable the Internet connection. A network message or valid cached data is shown.
TC05 Refresh the weather screen. The app attempts to retrieve updated information.
TC06 Open the forecast screen. Forecast information is displayed when supported by the API.
TC07 Deny location permission. The app continues to support manual city search.

28. Debugging Common Problems

Problem 1: API Request Fails

Possible causes: Incorrect base URL, missing permission, invalid credentials, connectivity issues, or incorrect query parameters.

Solution: Inspect the HTTP status code, verify the endpoint against provider documentation, and check the Internet permission.

Problem 2: JSON Parsing Fails

Possible causes: Incorrect field names, incompatible data types, or a nested response structure that differs from the model.

Solution: Compare the model with a real sample response and add the necessary serialization annotations or nested data classes.

Problem 3: Weather Information Does Not Update

Possible causes: The UI is not observing state changes, the request failed, or cached data is being displayed.

Solution: Verify the request result, update observable ViewModel state, and display the last-updated time.

Problem 4: City Search Returns the Wrong Location

Possible causes: Multiple cities share the same name or the provider uses a different location identifier.

Solution: Use geocoding and allow users to select the correct city and country.

Problem 5: The App Freezes During a Request

Possible causes: Blocking network calls run on the main thread.

Solution: Use Retrofit suspend functions, coroutines, and lifecycle-aware state management.

29. Security and Privacy Best Practices

  • Use HTTPS endpoints for API communication.
  • Avoid committing private credentials to source control.
  • Keep privileged API keys on a backend when they must remain confidential.
  • Do not log secrets or sensitive location information.
  • Request location permission only when required.
  • Explain location use clearly to users.
  • Handle API responses safely and validate unexpected data.
  • Follow the weather provider's terms and attribution requirements.
  • Use appropriate access controls if the app has a backend or user accounts.

30. Suggested Project Folder Structure

WeatherApp/
|
|-- data/
|   |-- remote/
|   |   |-- WeatherApiService.kt
|   |   |-- RetrofitClient.kt
|   |
|   |-- repository/
|       |-- WeatherRepository.kt
|
|-- model/
|   |-- WeatherResponse.kt
|   |-- ForecastResponse.kt
|
|-- ui/
|   |-- home/
|   |-- search/
|   |-- forecast/
|   |-- settings/
|
|-- viewmodel/
|   |-- WeatherViewModel.kt
|
|-- MainActivity.kt

This is a suggested project structure. Adjust the folders and classes to match the chosen UI framework and application architecture.

31. Future Enhancements

  • Hourly Forecast: Display temperature and conditions for upcoming hours.
  • Weather Alerts: Show official alerts when the selected provider supports them.
  • Multiple Cities: Save and switch between favorite locations.
  • Weather Widgets: Display selected weather details on the device home screen.
  • Unit Conversion: Allow Celsius, Fahrenheit, and supported wind-speed units.
  • Weather Maps: Integrate radar or map layers where available.
  • Notifications: Notify users about relevant forecast changes when supported and appropriate.
  • Offline Support: Display previously cached information with its update time.
  • Accessibility Improvements: Add readable labels and accessible descriptions for icons.

32. Practical Exercises

  1. Create a new Android project for the weather application.
  2. Configure the Internet permission.
  3. Select a weather API provider and review its documentation.
  4. Add Retrofit and a compatible JSON converter.
  5. Create a data model for the selected provider's response.
  6. Define the API interface and configure the Retrofit client.
  7. Implement city search and display current weather.
  8. Add loading and error states.
  9. Display weather icons and measurement units.
  10. Integrate a forecast endpoint.
  11. Add current-location weather with appropriate permission handling.
  12. Test invalid input, offline operation, and failed requests.
  13. Document the project and prepare a working demonstration.

33. Interview Questions and Answers

Q1. What is a REST API?

Answer: A REST API allows applications to communicate with a service through HTTP endpoints and exchange structured data.

Q2. What is JSON?

Answer: JSON is a lightweight text format used to represent structured data in API requests and responses.

Q3. What is Retrofit?

Answer: Retrofit is an HTTP client library for Android and Java that converts API endpoints into callable interface methods.

Q4. Why should network requests run asynchronously?

Answer: Network operations may take time. Running them asynchronously prevents the main UI thread from becoming blocked.

Q5. What is the purpose of a data model?

Answer: A data model represents the structure of information received from the API and makes it easier to access values in the application.

Q6. How should API errors be handled?

Answer: Inspect the response or exception, distinguish common failure types, display a useful message, and provide retry behavior when appropriate.

Q7. Why is an API key required?

Answer: A provider may use an API key to identify requests, enforce quotas, and control access to its services.

Q8. How can the application show weather for the current location?

Answer: Request appropriate location permission, obtain coordinates, and send them to a supported weather endpoint.

Q9. What is caching?

Answer: Caching stores previously retrieved data so it can be reused, reducing network requests and providing a possible fallback when offline.

Q10. How can duplicate API requests be reduced?

Answer: Use caching, debounce search input, cancel outdated requests, and avoid unnecessary refresh operations.

Q11. What is the role of a ViewModel?

Answer: A ViewModel manages UI-related data and state separately from the screen's rendering logic.

Q12. How should API credentials be protected?

Answer: Avoid committing credentials to source control and use a backend for privileged secrets that must not be exposed in a distributed application.

34. Quick Revision Checklist

  • Understand REST API and HTTP GET requests.
  • Select a suitable weather provider.
  • Configure Internet permission and dependencies.
  • Create response models that match the API schema.
  • Define Retrofit endpoints and the client.
  • Manage API credentials appropriately.
  • Use asynchronous network requests.
  • Display current weather and forecast information.
  • Implement city search and optional location access.
  • Handle loading, errors, and offline scenarios.
  • Test API responses and UI behavior.
  • Document the project and prepare a demonstration.

35. Conclusion

Developing a Weather App Using REST API Integration is a practical Android project that demonstrates how a mobile application communicates with an external service, parses JSON responses, and displays dynamic information.

Begin with city search and current-weather information. Once the basic request-and-response workflow is reliable, add forecasts, location-based weather, caching, favorite cities, and notifications. A well-structured networking layer, secure credential management, and clear error handling are essential for building a dependable application.

Explore the following resources to learn more about Android application development:

Previous Next
whatsapp