Response from the API

Asked

Viewed 24 times

0

I am implementing a Search function in a list, I want to get the answer from my API to see if it is correct for my Search. How do I get the response of a fun @GET from my API? I’m using Retrofit

function I want the answer to see if I’m getting correctly to put in Search:

@GET("v2/cards?q=name:")
suspend fun getPokemonsPesquisa(@Query("q") name: String): Response<PokemonsResponse>

Appretrofit:

private const val BASE_URL =  "https://api.pokemontcg.io/"

class AppRetrofit {
val client = OkHttpClient.Builder()
    .addInterceptor(AppInterceptor())
    .build()

private val retrofit by lazy {
    Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()
}
val pokemonService: API by lazy {
    retrofit.create(API::class.java)
 }

}

Appinterceptor:

class AppInterceptor : Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
    var original = chain.request()
    val url = original.url.newBuilder()
        .addQueryParameter("api_key", BuildConfig.API_KEY).build()
    original = original.newBuilder().url(url).build()
    return chain.proceed(original)

 }

}

1 answer

0


Since you’re using coroutine, you don’t need the return of your @GET method to be a Response<...>, just be your object PokemonsResponse direct. That is, modify your class API so that the method stays this way:

@GET("v2/cards?q=name:")
suspend fun getPokemonsPesquisa(@Query("q") name: String): PokemonsResponse

To call this method, you need to use that reference from pokemonService class AppRetrofit and call the method getPokemonsPesquisa in it, among a coroutine scope. The complete example depends on where you will call it exactly, but it may be something like:

viewModelScope.launch {
    try {
        val response = pokemonService.getPokemonsPesquisa("Scorbunny")
        // use o objeto response aqui
    } catch (ex: Exception) {
        // trate a exceção aqui
    }
}

(... in that case, if calling this method from a ViewModel, for example)

Browser other questions tagged

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