Retrofit & REST APIs
Make HTTP requests with Retrofit. Define API interfaces, parse JSON with Gson/Moshi, handle responses and errors, and integrate with coroutines.
Retrofit & REST APIs is a free Android Academy lesson on CoddyKit — lesson 1 of 6. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 6 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Retrofit?
Retrofit is the most popular HTTP client for Android, built by Square. It lets you define your REST API as a Kotlin interface — no boilerplate HTTP code.
- Annotate methods with
@GET,@POST, etc. - Auto-converts JSON responses to Kotlin data classes
- Native coroutine support (
suspend fun)
Adding Dependencies
Add Retrofit and Gson converter to app/build.gradle:
// app/build.gradle
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.11.0'
implementation 'com.squareup.retrofit2:converter-gson:2.11.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
}
// AndroidManifest.xml — add internet permission:
// <uses-permission android:name="android.permission.INTERNET" />Define the API Interface
Create a Kotlin interface describing your API endpoints:
import retrofit2.http.*
data class Post(val id: Int, val title: String, val body: String, val userId: Int)
interface ApiService {
@GET("posts")
suspend fun getPosts(): List<Post>
@GET("posts/{id}")
suspend fun getPost(@Path("id") id: Int): Post
@POST("posts")
suspend fun createPost(@Body post: Post): Post
@GET("posts")
suspend fun getPostsByUser(@Query("userId") userId: Int): List<Post>
}Build the Retrofit Instance
Create a singleton Retrofit instance — typically in an object or via Hilt:
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "https://jsonplaceholder.typicode.com/"
val api: ApiService by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
}
}Making a GET Request
Call the API from a Repository using Kotlin coroutines:
class PostRepository {
private val api = RetrofitClient.api
suspend fun getPosts(): List<Post> {
return api.getPosts() // Retrofit handles threading for you
}
suspend fun getPost(id: Int): Post {
return api.getPost(id)
}
}
// In ViewModel:
fun loadPosts() {
viewModelScope.launch {
try {
val posts = withContext(Dispatchers.IO) {
repository.getPosts()
}
_posts.value = posts
} catch (e: Exception) {
_error.value = "Network error: ${e.message}"
}
}
}Gson JSON Mapping
Gson converts JSON to Kotlin data classes automatically. Field names must match the JSON keys, or use @SerializedName:
import com.google.gson.annotations.SerializedName
data class User(
val id: Int,
val name: String,
val email: String,
@SerializedName("phone_number") // JSON key is 'phone_number'
val phoneNumber: String,
@SerializedName("created_at")
val createdAt: String
)POST Request with a Body
Send data to a server using @POST and @Body:
// API interface:
@POST("users")
suspend fun createUser(@Body user: User): User
// In Repository:
suspend fun createUser(name: String, email: String): User {
val newUser = User(id = 0, name = name, email = email, phoneNumber = "", createdAt = "")
return api.createUser(newUser)
}
// In ViewModel:
fun registerUser(name: String, email: String) {
viewModelScope.launch {
val user = withContext(Dispatchers.IO) {
repo.createUser(name, email)
}
_registeredUser.value = user
}
}Headers & Authentication
Add headers to every request using an OkHttp interceptor:
import okhttp3.OkHttpClient
import okhttp3.Interceptor
val authClient = OkHttpClient.Builder()
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer $token")
.addHeader("Accept", "application/json")
.build()
chain.proceed(request)
}
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(authClient) // use our authenticated client
.addConverterFactory(GsonConverterFactory.create())
.build()Handling HTTP Errors
A successful HTTP response (200-299) returns a value. Error responses (4xx, 5xx) throw an HttpException. Always handle both:
HttpException— server returned an error status codeIOException— no network connection
Quick Check
Which Retrofit annotation maps a method parameter to a URL path segment like /posts/{id}?
Recap: Retrofit & APIs
You can now fetch data from any REST API:
- Define API with a Kotlin interface + annotations (@GET, @POST, @Path, @Query)
- Build a Retrofit instance with a base URL and Gson converter
- Call suspend functions from a coroutine in the ViewModel
- Map JSON → Kotlin data classes automatically
- Handle
HttpExceptionandIOException
Next: display network images with Coil.
Frequently asked questions
Is the “Retrofit & REST APIs” lesson free?
Yes — the full text of “Retrofit & REST APIs” is free to read here on the web, and the Android Academy course includes 6 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.
What will I learn in “Retrofit & REST APIs”?
Make HTTP requests with Retrofit. Define API interfaces, parse JSON with Gson/Moshi, handle responses and errors, and integrate with coroutines. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Android Academy?
No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 6, so you can start here or from the beginning and move at your own pace.
How long does the “Retrofit & REST APIs” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Android Academy lesson?
Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.