0
0
Android Kotlinmobile~5 mins

Retrofit setup in Android Kotlin

Choose your learning style9 modes available
Introduction

Retrofit helps your app talk to the internet easily. It turns web data into Kotlin objects so you can use them in your app.

When you want to get data from a website or online service.
When your app needs to send or receive information from a server.
When you want to handle web requests without writing complex code.
When you want to convert JSON data from the internet into Kotlin objects automatically.
Syntax
Android Kotlin
val retrofit = Retrofit.Builder()
    .baseUrl("https://yourapi.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

baseUrl is the main web address your app will use.

addConverterFactory tells Retrofit how to turn JSON into Kotlin objects.

Examples
Basic setup with Gson to convert JSON data.
Android Kotlin
val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()
Using Moshi instead of Gson for JSON conversion.
Android Kotlin
val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(MoshiConverterFactory.create())
    .build()
Sample App

This simple Kotlin program creates a Retrofit instance with a base URL and Gson converter. It then prints the base URL to confirm setup.

Android Kotlin
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

fun createRetrofit(): Retrofit {
    return Retrofit.Builder()
        .baseUrl("https://jsonplaceholder.typicode.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

fun main() {
    val retrofit = createRetrofit()
    println("Retrofit instance created with base URL: ${retrofit.baseUrl()}")
}
OutputSuccess
Important Notes

Always use a trailing slash / at the end of your base URL.

Make sure to add the Retrofit and converter dependencies in your build.gradle file.

Retrofit setup is the first step before making network calls.

Summary

Retrofit simplifies network calls by converting web data to Kotlin objects.

Setup requires a base URL and a converter like Gson.

Once set up, you can easily create services to fetch or send data.