DEV Community

Cover image for Connecting an Android App to a REST API Using Retrofit in Java
Dhananjay Bagul
Dhananjay Bagul

Posted on

Connecting an Android App to a REST API Using Retrofit in Java

When building an Android application, we often need to communicate with a backend server to fetch or send data. For example, an HRMS app may need to display employees, a shopping app may need to load products, or a booking app may need to retrieve reservations.

One popular way to make these network requests in Android is Retrofit.

In this article, we will learn how to connect an Android application to a REST API using Java and Retrofit, step by step.

What Is Retrofit?

Retrofit is a type-safe HTTP client for Android and Java. It helps us make API requests without writing all the networking code manually.

With Retrofit, we can:

Send GET requests to fetch data.

Send POST requests to submit data.

Convert JSON responses into Java objects using a converter.

Handle successful responses and network errors.

Keep API-related code organized in a separate interface.

  1. Add Retrofit Dependencies

Open your app-level build.gradle file and add these dependencies inside dependencies:

implementation 'com.squareup.retrofit2:retrofit:2.11.0'
implementation 'com.squareup.retrofit2:converter-gson:2.11.0'

Sync the project after adding them. If your project uses build.gradle.kts, use the Kotlin DSL syntax for dependencies.

  1. Add Internet Permission

Open AndroidManifest.xml and add this permission above the tag:

This permission allows your application to access the internet.

  1. Create a Java Model Class

Suppose our backend returns employee information in JSON format:

{
"id": 1,
"name": "Rahul",
"email": "rahul@example.com"
}

Create a Java class named Employee.java:

public class Employee {

private int id;
private String name;
private String email;

public int getId() {
    return id;
}

public String getName() {
    return name;
}

public String getEmail() {
    return email;
}
Enter fullscreen mode Exit fullscreen mode

}

Gson converts the JSON response into an Employee object when the JSON field names match the Java fields.

  1. Create the API Interface

Create a file named ApiService.java:

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiService {

@GET("api/employees")
Call<List<Employee>> getEmployees();
Enter fullscreen mode Exit fullscreen mode

}

The @get annotation tells Retrofit to send a GET request to the api/employees endpoint.

Replace this endpoint with the path exposed by your own backend API.

  1. Configure Retrofit

Create a class named ApiClient.java:

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

public class ApiClient {

private static final String BASE_URL =
        "https://your-domain.com/";

private static Retrofit retrofit;

public static ApiService getApiService() {

    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(
                        GsonConverterFactory.create()
                )
                .build();
    }

    return retrofit.create(ApiService.class);
}
Enter fullscreen mode Exit fullscreen mode

}

Replace https://your-domain.com/ with your backend's base URL. Keep the trailing slash because Retrofit requires the base URL to end with /.

For local testing with the Android emulator, a backend running on your development computer can often be reached using http://10.0.2.2:8080/. Configure local HTTP access appropriately for development, or use HTTPS.

  1. Make an API Request from an Activity

Now, call the API from your Activity:

import android.widget.Toast;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

ApiService apiService = ApiClient.getApiService();

apiService.getEmployees().enqueue(
new Callback>() {

@Override
public void onResponse(
        Call<List<Employee>> call,
        Response<List<Employee>> response) {

    if (response.isSuccessful()
            && response.body() != null) {

        List<Employee> employees = response.body();

        // Pass the employee list to your RecyclerView adapter.

    } else {
        Toast.makeText(
                MainActivity.this,
                "Unable to load employees",
                Toast.LENGTH_SHORT
        ).show();
    }
}

@Override
public void onFailure(
        Call<List<Employee>> call,
        Throwable t) {

    Toast.makeText(
            MainActivity.this,
            "Network error: " + t.getMessage(),
            Toast.LENGTH_SHORT
    ).show();
}
Enter fullscreen mode Exit fullscreen mode

});

This example assumes the request is made inside MainActivity. In a real project, keep the networking logic in an appropriate class and update your UI through your chosen architecture.

The important part is enqueue(). It executes the request asynchronously, so the network call does not block the main UI thread.

  1. Connect It to a Spring Boot Backend

If your backend is built with Spring Boot, it might expose an endpoint like this:

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

@GetMapping
public List<Employee> getEmployees() {
    return employeeService.getAllEmployees();
}
Enter fullscreen mode Exit fullscreen mode

}

The Android endpoint and the Spring Boot route must match. The controller's response should also return JSON in a structure that your Android model can parse.

Once the response arrives, you can pass the employee list to a RecyclerView.Adapter and display each employee inside a card or list item.

Common Mistakes to Avoid

Incorrect base URL: Make sure the server address and endpoint path are correct.

Missing internet permission: Check AndroidManifest.xml if requests never reach the server.

Mismatched JSON fields: Verify that the backend's JSON response matches your model class.

Testing with localhost: The Android emulator's localhost refers to the emulator itself, not your development computer.

Ignoring errors: Handle unsuccessful HTTP responses as well as network failures.

Using insecure production URLs: Prefer HTTPS for production applications and never expose passwords, private keys, or sensitive tokens in source code.

Conclusion

Retrofit makes it easier to connect an Android application to a REST API using Java. By separating the model class, API interface, and Retrofit client, we can keep our code cleaner and easier to maintain.

Whether you are building an HRMS application, an e-commerce app, or a booking system, learning Retrofit is a valuable skill for Android development.

Start with a simple GET request, verify the JSON response, and then move on to POST, PUT, and DELETE operations as your project grows.

What API integration are you working on in your Android project? Share your experience in the comments.

Top comments (1)

Collapse
 
suppdevbot profile image
DEV SUPPORTS •
You need to verify your account.
Enter fullscreen mode Exit fullscreen mode

tr.ee/dev-to