Home > Software design >  Retrofit GET Query with api key:
Retrofit GET Query with api key:

Time:02-12

Hello I am trying to use Retrofit to access a URL : https://my.api.mockaroo.com/products?key=57b501f0

here is my interface:

interface ProductInterface {
    @GET("products?")
    suspend fun getTodos(@Query("key") key: String): Response<List<product>>
}

here is my Retrofit Object

object RetrofitInstance {
    val api: ProductInterface by lazy<ProductInterface> {
        Log.e("Request", "Sent")
        Retrofit.Builder()
            .baseUrl("https://my.api.mockaroo.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ProductInterface::class.java)
    }
}

and here it is how i am accessing it:

RetrofitInstance.api.getTodos("57b501f0")

But When i logged its working, It says following URL: https://my.api.mockaroo.com/products?&key=57b501f0

was accessed instead of : https://my.api.mockaroo.com/products?key=57b501f0

How can i resolve this?

CodePudding user response:

Try this way maybe:

interface ProductInterface {
    @GET("products?key=57b501f0")
    suspend fun getTodos(): Response<List<product>>
}

AND instead of RetrofitInstance.api.getTodos("57b501f0") write

RetrofitInstance.api.getTodos()

-----OR-----

Just remove the question mark after products.

interface ProductInterface {
    @GET("products")
    suspend fun getTodos(@Query("key") key: String): Response<List<product>>
}

CodePudding user response:

In retrofit when you pass the queries,it will append to the URL with questionmark(?).if there is more than one queries is append then it uses the & sign for that so you have already mentioned the ? in the @GET("products?") so its considering the query added in the request as extra so its using the & for that.please remove the ? from the @GET("products?") .it will work fine

interface ProductInterface {
    @GET("products")
    suspend fun getTodos(@Query("key") key: String): Response<List<product>>
}

Refer this link for more info about Api Request

  • Related