Skip to main content

How to define API endpoints using Retrofit annotations in Kotlin Android

How to define API endpoints using Retrofit annotations in Kotlin Android.

Here's a step-by-step tutorial on how to define API endpoints using Retrofit annotations 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 line to the dependencies section:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

Step 2: Create a Retrofit instance

Next, create a Retrofit instance in your code. This instance will be used to make API requests. Create a new Kotlin class and add the following code:

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

Step 3: Define the API interface

Now, create an interface that defines your API endpoints. Each method in this interface represents a specific API request. Add the following code to your Kotlin class:

interface ApiService {
@GET("users")
suspend fun getUsers(): List<User>

@POST("users")
suspend fun createUser(@Body user: User): User
}

In this example, we have two endpoints: getUsers which performs a GET request to retrieve a list of users, and createUser which performs a POST request to create a new user. Replace User with your own data model class.

Step 4: Create an instance of the API interface

Create an instance of the API interface using the Retrofit instance we created earlier. Add the following code to your Kotlin class:

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

Step 5: Make API requests

Now you can use the apiService instance to make API requests. You can call the methods defined in the API interface to perform different types of requests. Here are a few examples:

Example 1: Making a GET request to retrieve a list of users

try {
val users = apiService.getUsers()
// Process the list of users
} catch (e: Exception) {
// Handle the exception
}

Example 2: Making a POST request to create a new user

val newUser = User("John Doe", "[email protected]")
try {
val createdUser = apiService.createUser(newUser)
// Handle the created user
} catch (e: Exception) {
// Handle the exception
}

Replace User("John Doe", "[email protected]") with the actual data you want to send to the server.

That's it! You have now defined API endpoints using Retrofit annotations in Kotlin Android. You can further customize your API requests by adding query parameters, headers, and other annotations to the methods in your API interface.