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.
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.
// 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
}
});
YOUR_API_KEY
with your actual API key from OpenWeatherMap.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.
// 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
}
});
LoginRequest
and LoginResponse
class to handle the login data structure.Suppose you are developing a photo-sharing app where users can upload images. You can utilize Retrofit to handle image uploads to a server.
// 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
}
});
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.