Introduction
We use API interfaces to tell our app how to talk to web services. It helps us get or send data easily.
We use API interfaces to tell our app how to talk to web services. It helps us get or send data easily.
interface ApiService {
@GET("endpoint")
suspend fun getData(): Response<DataType>
}interface ApiService {
@GET("users")
suspend fun getUsers(): Response<List<User>>
}interface ApiService {
@POST("login")
suspend fun loginUser(@Body loginInfo: LoginRequest): Response<LoginResponse>
}This interface defines a GET request to fetch posts from a web service. Each post has an id, title, and body.
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)
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.
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.
@POST("login")
fun loginUser(@Body user: User): Call<Response>
What happens when loginUser is called?@GET("users/{id}")
fun getUser(@Path userId: Int): Call<User>Pass the test and this pattern moves unknown