Skip to main content

How to pass query parameters with Retrofit in Kotlin Android

How to pass query parameters with Retrofit in Kotlin Android.

Here's a step-by-step tutorial on how to pass query parameters with Retrofit in Kotlin Android:

Step 1: Set up Retrofit

First, you need to add the Retrofit library to your project. Open your project's build.gradle file and add the following dependencies:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Once you've added the dependencies, sync your project.

Step 2: Create a Retrofit instance

Next, create a Retrofit instance in your Kotlin class. You can do this by creating a singleton class or using a dependency injection framework like Dagger.

val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/") // Replace with your API base URL
.addConverterFactory(GsonConverterFactory.create())
.build()

Step 3: Define your API interface

Create an interface that defines your API endpoints. Annotate each method with the appropriate HTTP method (e.g., @GET, @POST, etc.) and specify the query parameters using the @Query annotation.

interface ApiService {
@GET("users")
suspend fun getUsers(@Query("page") page: Int, @Query("limit") limit: Int): List<User>
}

Step 4: Create an instance of the API interface

Now, create an instance of the API interface using the Retrofit instance created earlier.

val apiService = retrofit.create(ApiService::class.java)

Step 5: Make a request with query parameters

Finally, you can make a request to your API endpoint using the defined method and pass the query parameters as arguments.

val page = 1
val limit = 10

val users = apiService.getUsers(page, limit)

In the above example, the getUsers method takes two query parameters: page and limit. These parameters will be appended to the URL as query parameters when the request is made.

That's it! You have successfully passed query parameters with Retrofit in Kotlin Android.

Additional notes:

  • You can also pass query parameters as a Map using the @QueryMap annotation if you have a dynamic number of parameters.
  • If your query parameter value is nullable, you can use the @Query annotation's encoded parameter to control whether the parameter should be included in the URL or ignored when the value is null.

I hope this tutorial helps you understand how to pass query parameters with Retrofit in Kotlin Android. Let me know if you have any further questions!