How to Post Data to API using Retrofit in Android using Jetpack Compose? (original) (raw)

Last Updated : 23 Jul, 2025

APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retrofit in Android using Jetpack Compose.

**Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only available in Kotlin. It uses features such as coroutines, and the handling of @Composable annotations is handled by a Kotlin compiler. There is no method for Java to access these. Therefore, you cannot use Jetpack Compose if your project does not support Kotlin.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.

**Note: Select **Kotlin as the programming language.

Step 2: Add the below dependency to your build.gradle File

Navigate to the **Gradle Scripts > build.gradle.kts (Module:app) and add the below dependency in the dependencies section.

dependencies {
...
implementation ("com.squareup.retrofit2:retrofit:2.9.0")
implementation ("com.squareup.retrofit2:converter-gson:2.5.0")
}

After adding this dependency **sync your project.

Step 3: Adding Internet Permissions in the AndroidManifest.xml File

Navigate to the **app > AndroidManifest.xml and add the below code to it.

Step 4: Creating a Model Class for Storing Our Data

Navigate to the **app > kotlin+java > {package-name} > Right-click > New > Kotlin Class/File and name it as **DataModel and add the below code to it. Comments are added inside the code to understand the code in more detail.

**DataModel.kt:

Kotlin `

package com.geeksforgeeks.demo

data class DataModel( var name: String, var job: String )

`

Step 5: Creating an Interface Class for Our API Call

Navigate to the **app > kotlin+java > {package-name} > Right-click > New > Kotlin Class/File select it as **Interface and name the file as **RetrofitAPI and add below code to it. Comments are added inside the code to understand the code in more detail.

**RetrofitAPI.kt:

Kotlin `

package com.geeksforgeeks.demo

import retrofit2.Call import retrofit2.http.*

interface RetrofitAPI {

// POST annotation used to make a
// post request and pass parameter
@POST("users")
fun postData(@Body dataModel: DataModel?): Call<DataModel?>?

// In line above we are creating
// a method to post our data.

}

`

Step 6: Working with the MainActivity.java file

Go to the **MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

**MainActivity.kt:

Kotlin `

package com.geeksforgeeks.demo

import android.content.Context import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.* import androidx.compose.ui.graphics.* import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.* import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.* import com.geeksforgeeks.demo.ui.theme.DemoTheme import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DemoTheme(dynamicColor = false, darkTheme = false) { Surface(color = Color.White) { PostData() } } } } }

@Composable fun PostData() { val context = LocalContext.current

val userName = remember {
    mutableStateOf(TextFieldValue())
}
val job = remember {
    mutableStateOf(TextFieldValue())
}
val response = remember {
    mutableStateOf("")
}

Column(
    modifier = Modifier
        .fillMaxSize()
        .fillMaxHeight()
        .fillMaxWidth(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    // Email text field
    TextField(
        value = userName.value,
        onValueChange = { userName.value = it },
        placeholder = { Text(text = "Enter your name") },
        singleLine = true
    )

    Spacer(modifier = Modifier.height(5.dp))

    // Job text field
    TextField(
        value = job.value,
        onValueChange = { job.value = it },
        placeholder = { Text(text = "Enter your job") },
        singleLine = true
    )

    Spacer(modifier = Modifier.height(10.dp))

    Button(
        onClick = {
            
            // API call
            postDataUsingRetrofit(context, userName, job, response)
        }
    ) {
        Text(text = "Post Data", modifier = Modifier.padding(8.dp))
    }

    Spacer(modifier = Modifier.height(20.dp))

    Text(
        text = response.value,
        color = Color.Black,
        fontSize = 20.sp,
        fontWeight = FontWeight.Bold, modifier = Modifier
            .padding(10.dp)
            .fillMaxWidth(),
        textAlign = TextAlign.Center
    )
}

}

private fun postDataUsingRetrofit( ctx: Context, userName: MutableState, job: MutableState, result: MutableState ) { // base url val url = "https://reqres.in/api/"

// create retrofit builder and load
// json data in model class
val retrofit = Retrofit.Builder()
    .baseUrl(url)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

// create instance of our retrofit API
val retrofitAPI = retrofit.create(RetrofitAPI::class.java)

// fetch data from text fields and
// pass to our model class
val dataModel = DataModel(userName.value.text, job.value.text)

// API call to make post request
val call: Call<DataModel?>? = retrofitAPI.postData(dataModel)
call!!.enqueue(object : Callback<DataModel?> {
    override fun onResponse(call: Call<DataModel?>, response: Response<DataModel?>) {

        // received a response
        Toast.makeText(ctx, "Data posted to API", Toast.LENGTH_SHORT).show()

        // pass response to our model class
        val model: DataModel? = response.body()

        // setting text to our text field
        val resp = "Response Code : " + response.code() + "\n" + "User Name : " + model!!.name + "\n" + "Job : " + model.job
        result.value = resp
    }

    override fun onFailure(call: Call<DataModel?>, t: Throwable) {
        // passing error message
        result.value = "Error found is : " + t.message
    }
})

}

`

Output: