What is the Retrofit?

Asked

Viewed 1,773 times

6

I am using the retrofit in an application to consume a Java Web Service and I am in doubt:

Retrofit is a library or API?

  • I imagine Retrofit is a library that has an API

2 answers

4


What is the Retrofit

Retrofit is a library developed by Square that is used as a REST Client on Android and Java. Uses library Okhttp to make the Http Requests.

Retrofit makes it easy to recover and upload JSON through a Web service REST. With Retrofit you can choose which converter to use for data serialization, such as GSON.

4

Retrofit is a Java library to create type-safe HTTP secure clients for Android applications

How so type-safe?

The safety provided by retrofit is that it originally requires the developer to develop a interface. If you are new to the world of Java and don’t know what a interface i recommend reading that contents.

But making a brief summary, a interface is a type of contract, in which you to use specific features it is necessary to implement the methods present in your interface. The type-safe Retrofit comes due to this, because you should in your interface define the requests that your client will use and in what type of data structure it should return, for example:

// Interface para o endpoit de repositórios de um usuário específico
public interface GitHubService {
   @GET("users/{user}/repos")
   Call<List<Repo>> listRepos(@Path("user") String user);

   // Defina aqui outros métodos com os mais variados tipos de retorno
}

The implementation would be as follows.

// Configuração do Retrofit
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();
// Objeto que implementa a interface
GitHubService service = retrofit.create(GitHubService.class);

// Como o método "listRepos" da interface "GitHubService" retorna um 
// Call<List<Repo>> vamos criar um objeto equivalete.
Call<List<Repo>> repos = service.listRepos("octocat");

This way you can make it very clear what kind of data each endpoit should bring. And if your app uses more than one service, you can create a package example.services where all its interfaces will be present. Leaving your project more organized.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.