How to Make API Call in Android Kotlin: Simple Guide
To make an API call in Android Kotlin, use the
Retrofit library which simplifies HTTP requests. Define an interface for your API endpoints, create a Retrofit instance, and call the API asynchronously with enqueue to handle responses on the main thread.Syntax
Making an API call with Retrofit involves these steps:
- Define API interface: Declare HTTP methods and endpoints.
- Create Retrofit instance: Set base URL and converter.
- Make call: Use the interface to request data asynchronously.
kotlin
interface ApiService {
@GET("users")
fun getUsers(): Call<List<User>>
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val service = retrofit.create(ApiService::class.java)
val call = service.getUsers()
call.enqueue(object : Callback<List<User>> {
override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
// handle success
}
override fun onFailure(call: Call<List<User>>, t: Throwable) {
// handle failure
}
})Example
This example shows a simple API call to fetch a list of users and print their names in the log.
kotlin
data class User(val id: Int, val name: String) interface ApiService { @GET("users") fun getUsers(): Call<List<User>> } fun fetchUsers() { val retrofit = Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com/") .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(ApiService::class.java) val call = service.getUsers() call.enqueue(object : Callback<List<User>> { override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) { if (response.isSuccessful) { response.body()?.forEach { user -> Log.d("API", "User: ${user.name}") } } else { Log.e("API", "Error: ${response.code()}") } } override fun onFailure(call: Call<List<User>>, t: Throwable) { Log.e("API", "Failure: ${t.message}") } }) }
Output
Log output:
User: Leanne Graham
User: Ervin Howell
User: Clementine Bauch
... (list of user names)
Common Pitfalls
Common mistakes when making API calls in Android Kotlin include:
- Not adding internet permission in
AndroidManifest.xml. - Making network calls on the main thread causing app freeze.
- Not handling null or error responses properly.
- Forgetting to add a converter like Gson for JSON parsing.
Always use enqueue for asynchronous calls to avoid blocking UI.
kotlin
/* Wrong: synchronous call on main thread (causes crash) */ val response = service.getUsers().execute() // Don't do this on main thread /* Right: asynchronous call */ service.getUsers().enqueue(object : Callback<List<User>> { override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) { // handle success } override fun onFailure(call: Call<List<User>>, t: Throwable) { // handle failure } })
Quick Reference
Tips for making API calls in Android Kotlin:
- Use Retrofit with GsonConverterFactory for JSON APIs.
- Always perform calls asynchronously with
enqueue. - Check
response.isSuccessfulbefore using data. - Handle errors in
onFailurecallback. - Add
<uses-permission android:name="android.permission.INTERNET" />in manifest.
Key Takeaways
Use Retrofit library to simplify API calls in Android Kotlin.
Always make network requests asynchronously with enqueue to avoid freezing UI.
Add internet permission in AndroidManifest.xml to allow network access.
Handle success and failure responses properly to avoid crashes.
Use GsonConverterFactory to parse JSON responses automatically.