Using RESTful APIs with Retrofit in Android Apps

Explore practical examples of using RESTful APIs with Retrofit in Android apps to enhance functionality and user experience.
By Jamie

Introduction

Using RESTful APIs with Retrofit in Android apps allows developers to seamlessly connect their applications to web services. Retrofit is a powerful library that simplifies API integration by handling network calls and parsing responses. In this article, we will explore three practical examples of using RESTful APIs with Retrofit in Android apps, showcasing various use cases and implementation details.

Example 1: Fetching Weather Data

Use Case

Imagine you are developing a weather application that displays current weather conditions based on the user’s location. To achieve this, you can use a public weather API, such as OpenWeatherMap, to retrieve weather data.

Example Code

// Define the API interface
public interface WeatherApiService {
    @GET("weather")
    Call<WeatherResponse> getCurrentWeather(@Query("q") String city, @Query("appid") String apiKey);
}

// Set up Retrofit
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.openweathermap.org/data/2.5/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

WeatherApiService weatherApiService = retrofit.create(WeatherApiService.class);

// Making the API call
Call<WeatherResponse> call = weatherApiService.getCurrentWeather("London", "YOUR_API_KEY");
call.enqueue(new Callback<WeatherResponse>() {
    @Override
    public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            WeatherResponse weather = response.body();
            // Update UI with weather data
        }
    }

    @Override
    public void onFailure(Call<WeatherResponse> call, Throwable t) {
        // Handle the error
    }
});

Notes

  • Ensure you replace YOUR_API_KEY with your actual API key from OpenWeatherMap.
  • This example demonstrates basic error handling. You may want to expand it to manage different error scenarios, such as network issues or invalid API keys.

Example 2: User Authentication with JSONPlaceholder

Use Case

In this instance, you are building a mobile app that requires user authentication. You can use a mock API like JSONPlaceholder to simulate logging in users.

Example Code

// Define the API interface
public interface AuthApiService {
    @POST("users/login")
    Call<LoginResponse> loginUser(@Body LoginRequest loginRequest);
}

// Set up Retrofit
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://jsonplaceholder.typicode.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

AuthApiService authApiService = retrofit.create(AuthApiService.class);

// Creating login request
LoginRequest loginRequest = new LoginRequest("username", "password");
Call<LoginResponse> call = authApiService.loginUser(loginRequest);
call.enqueue(new Callback<LoginResponse>() {
    @Override
    public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            String token = response.body().getToken();
            // Handle successful login
        }
    }

    @Override
    public void onFailure(Call<LoginResponse> call, Throwable t) {
        // Handle login failure
    }
});

Notes

  • This example uses a LoginRequest and LoginResponse class to handle the login data structure.
  • JSONPlaceholder is a mock API, so it does not handle actual authentication. This example is meant for demonstration purposes only.

Example 3: Uploading Images to a Server

Use Case

Suppose you are developing a photo-sharing app where users can upload images. You can utilize Retrofit to handle image uploads to a server.

Example Code

// Define the API interface
public interface ImageUploadApiService {
    @Multipart
    @POST("upload")
    Call<UploadResponse> uploadImage(@Part MultipartBody.Part image);
}

// Set up Retrofit
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://yourapi.com/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

ImageUploadApiService imageUploadApiService = retrofit.create(ImageUploadApiService.class);

// Preparing the image file
File imageFile = new File(imagePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), imageFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", imageFile.getName(), requestFile);

// Making the API call
Call<UploadResponse> call = imageUploadApiService.uploadImage(body);
call.enqueue(new Callback<UploadResponse>() {
    @Override
    public void onResponse(Call<UploadResponse> call, Response<UploadResponse> response) {
        if (response.isSuccessful()) {
            // Handle successful upload
        }
    }

    @Override
    public void onFailure(Call<UploadResponse> call, Throwable t) {
        // Handle upload failure
    }
});

Notes

  • Ensure that your server endpoint is configured to handle multipart file uploads.
  • You may want to add progress tracking for larger files to improve user experience.

By leveraging these examples of using RESTful APIs with Retrofit in Android apps, you can enhance your application’s functionality, providing users with rich, data-driven experiences. Explore these implementations and adapt them to your specific project needs.