Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Retrofit Tutorial

Introduction

Retrofit is a type-safe HTTP client for Android and Java developed by Square. It allows developers to make HTTP requests to RESTful web services with ease. This tutorial will guide you through the basics of setting up and using Retrofit to make network requests in your Android applications.

Setting Up Retrofit

To start using Retrofit, you need to add the necessary dependencies to your project. Open your build.gradle file and add the following dependencies:

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

Sync your project to ensure the dependencies are added.

Creating a Retrofit Instance

To make network requests, you need to create an instance of Retrofit. Typically, this is done using a singleton pattern. Here is an example of how to create a Retrofit instance:

public class RetrofitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Defining API Endpoints

Next, you need to define the endpoints of your API. This is done using interfaces in Retrofit. For example, if you have a REST API with a GET endpoint, you would define it as follows:

public interface ApiService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}

Making Network Requests

Once you have defined your API endpoints, you can make network requests. Here is an example of how to use the ApiService to make a GET request:

Retrofit retrofit = RetrofitClient.getClient("https://api.github.com/");
ApiService apiService = retrofit.create(ApiService.class);

Call<List<Repo>> call = apiService.listRepos("octocat");
call.enqueue(new Callback<List<Repo>>() {
    @Override
    public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
        if (response.isSuccessful()) {
            List<Repo> repos = response.body();
            // Handle the list of repositories
        }
    }

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

Handling Responses

Retrofit uses the Response class to handle HTTP responses. You can check if the response was successful using the isSuccessful() method and get the response body using the body() method. Here's an example:

call.enqueue(new Callback<List<Repo>>() {
    @Override
    public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
        if (response.isSuccessful()) {
            List<Repo> repos = response.body();
            // Handle the list of repositories
        } else {
            // Handle the error response
        }
    }

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

Using Converters

Retrofit supports various converters to handle different data formats. In this tutorial, we used the Gson converter to handle JSON. You can add other converters as needed. Here is an example of adding a Moshi converter:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(MoshiConverterFactory.create())
    .build();

Conclusion

Retrofit is a powerful and easy-to-use library for making network requests in Android applications. By following this tutorial, you should have a good understanding of how to set up and use Retrofit in your projects. Happy coding!