viernes, 29 de abril de 2022

Consumiendo API con Retrofit


Si has trabajado con microservicios o simplemente has necesitado consumir una API de terceros, notaste que este código no es muy bello y muchas veces se torna complejo.

Retrofit es un framework que viene para salvarnos. 

Veamos un ejemplo, queremos consultar info de los repositorios de github, la información que necesitamos es esta : (voy a trabajar en kotlin porque pinto, es similar en Java) 

import com.google.gson.annotations.SerializedName


data class Repo(

    @SerializedName("id")

    var id: Int? = null,

    @SerializedName("name")

    var name: String,

    @SerializedName("full_name")

    var fullName: String,

    @SerializedName("language")

    var language: String

) {}

Entonces lo que tengo que hacer es agregar estas dependencias a mi proyecto (uso gradle) :

// https://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit

implementation("com.squareup.retrofit2:retrofit:2.9.0")

implementation("com.squareup.retrofit2:converter-gson:2.9.0")

y luego tengo que crear una interface que represente el servicio que voy a consumir : 


interface GitHubClient {

    @GET("users/{user}/repos")

    fun listRepos(@Path("user") user: String?): Call<List<Repo?>?>?

}

Y por último debo construir este cliente y usarlo : 


        val retrofit = Retrofit.Builder()

            .baseUrl("https://api.github.com/")

            .addConverterFactory(GsonConverterFactory.create())

            .build()


        val gitHubClient = retrofit.create(GitHubClient::class.java)

        val repos = gitHubClient.listRepos(userName)?.execute()?.body()


Y listo!!    

Dejo link : 

https://square.github.io/retrofit/

No hay comentarios.:

Publicar un comentario