What is Retrofit?

I'm using retrofit in an application to consume a Java Web Service and I'm in doubt:

Is Retrofit a library or an API?

Author: Denis Rudnei de Souza, 2017-12-05

2 answers

What is Retrofit

Retrofit is a library developed by Square that is used as a client REST on Android and Java. Use the library OkHttp to make the Http Requests.

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

 4
Author: Edilson Ngulele, 2017-12-30 07:54:38

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

What do you mean type-safe?

The security provided by retrofit is the fact that it originally required the developer to develop a interface. If you are new to the world of Java and do not know what a interface is I recommend reading this content.

But making a brief summary, a interface is a type of contract, in which you to utilize resources it is necessary to implement the methods present in your interface. The type-safe of Retrofit comes due to this, because you must 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 look like this.

// 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 type of data each endpoit should bring. And if your app uses more than one service, you can create a package example.services in which all its interfaces will be present. Making your project more organized.

 4
Author: Yago Azedias, 2018-02-19 11:03:39