0
0
Android Kotlinmobile~5 mins

API interface definition in Android Kotlin

Choose your learning style9 modes available
Introduction

We use API interfaces to tell our app how to talk to web services. It helps us get or send data easily.

When your app needs to get data from the internet, like weather or news.
When you want to send user info to a server, like login details.
When you want to keep your app updated with live data from a web service.
When you want to organize how your app talks to different web services clearly.
Syntax
Android Kotlin
interface ApiService {
    @GET("endpoint")
    suspend fun getData(): Response<DataType>
}
Use @GET, @POST, and other annotations to define HTTP methods.
The interface methods describe the web requests your app can make.
Examples
This defines a GET request to fetch a list of users.
Android Kotlin
interface ApiService {
    @GET("users")
    suspend fun getUsers(): Response<List<User>>
}
This defines a POST request to send login info and get a response.
Android Kotlin
interface ApiService {
    @POST("login")
    suspend fun loginUser(@Body loginInfo: LoginRequest): Response<LoginResponse>
}
Sample App

This interface defines a GET request to fetch posts from a web service. Each post has an id, title, and body.

Android Kotlin
import retrofit2.Response
import retrofit2.http.GET

interface ApiService {
    @GET("posts")
    suspend fun getPosts(): Response<List<Post>>
}

data class Post(val id: Int, val title: String, val body: String)
OutputSuccess
Important Notes

API interfaces are usually used with libraries like Retrofit in Android.

Use suspend functions to work smoothly with Kotlin coroutines for background tasks.

Always match the endpoint strings with the actual web service URLs.

Summary

API interfaces define how your app talks to web services.

Use annotations like @GET and @POST to specify request types.

Interface methods describe the data your app sends or receives.