Retrofit & REST APIs
Make HTTP requests with Retrofit. Define API interfaces, parse JSON with Gson/Moshi, handle responses and errors, and integrate with coroutines.
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" />