0
0
Android Kotlinmobile~15 mins

API interface definition in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: API Interface Definition Screen
This screen shows how to define a simple API interface in Kotlin for Android using Retrofit. It defines endpoints to fetch a list of items and a single item by ID.
Target UI
-------------------------
| API Interface Example  |
|-----------------------|
| GET /items            |
| GET /items/{id}       |
|-----------------------|
| Define interface with |
| Retrofit annotations  |
-------------------------
Create a Kotlin interface named ApiService
Define a function to get a list of items with @GET("items")
Define a function to get a single item by ID with @GET("items/{id}") and @Path parameter
Use Retrofit Call<T> as return type for both functions
Starter Code
Android Kotlin
package com.example.api

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path

// TODO: Define ApiService interface here
Task 1
Task 2
Task 3
Solution
Android Kotlin
package com.example.api

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path

interface ApiService {
  @GET("items")
  fun getItems(): Call<List<Item>>

  @GET("items/{id}")
  fun getItemById(@Path("id") id: Int): Call<Item>
}

// Data class for Item
data class Item(val id: Int, val name: String)

We define an interface ApiService with Retrofit annotations to specify HTTP methods and endpoints.

The @GET("items") annotation marks getItems() as a GET request to the "items" endpoint, returning a list of Item.

The @GET("items/{id}") annotation marks getItemById() as a GET request to "items/{id}" where {id} is a path parameter injected by @Path("id").

Both functions return Call objects from Retrofit, which can be used to enqueue network requests asynchronously.

Final Result
Completed Screen
-------------------------
| API Interface Example  |
|-----------------------|
| GET /items            |
| GET /items/{id}       |
|-----------------------|
| interface ApiService { |
|   fun getItems()      |
|   fun getItemById(id) |
| }                     |
-------------------------
No user interaction - this is a code definition screen
Used by Retrofit to make network calls in the app
Stretch Goal
Add a POST method to create a new item with @Body parameter
💡 Hint
Use @POST("items") and a function like createItem(@Body item: Item): Call<Item>