What is Retrofit?

6

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

  

Is Retrofit a library or an API?

    
asked by anonymous 06.12.2017 / 00:25

2 answers

3
  
    

What is Retrofit

  

Retrofit is a library developed by Square that is used as a REST Client in Android and Java. Use the OkHttp library to do the Http Requests

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

    
30.12.2017 / 08:54
3

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

How so type-safe ?

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

But briefly summarizing, interface is a type of contract, in which you use specific methods to implement the methods present in your interface . The% of Retrofit% comes because of 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 clear what kind of data each endpoit should bring. And if your app uses more than one service, you can create a package type-safe in which all your interfaces will be present. Leaving your project more organized.

    
19.02.2018 / 12:03