Open In App
Related Articles

How to Post Data to API using Retrofit in Android?

Improve Article
Save Article
Like Article

We have seen reading data from API in our Android app in Android Studio. For reading data from API, we use GET request to read our data which is in JSON format. In this article, we will take a look at adding data to REST API in our Android App in Android Studio. 

What we are going to build in this article? 

We will be building a simple application in which we will be adding data to our REST API using the Retrofit library with POST Request. We will add the data through edit text fields and we will verify through response code that our data has been added to the API or not. When we added data to our API we will get to see 201 as a response code. 201 response code means data has been added to our API. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Data can be added to API in different formats such as XML Form and JSON. Most of the APIs post their data in JSON format. So we will also be posting our data to our API in the form of the JSON object.  

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add the below dependency in your build.gradle file

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

// below dependency for using the retrofit

implementation ‘com.squareup.retrofit2:retrofit:2.9.0’

implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’

After adding this dependency sync your project and now move towards the AndroidManifest.xml part.  

Step 3: Adding permissions to the internet in the AndroidManifest.xml file

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


<!--permissions for INTERNET-->
<uses-permission android:name="android.permission.INTERNET"/>

Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 


<?xml version="1.0" encoding="utf-8"?>
    <!--edit text field for adding name-->
        android:hint="Enter your name" />
    <!--edit text for adding job-->
        android:hint="Enter your job" />
    <!--button for adding data-->
        android:text="Send Data to API"
        android:textAllCaps="false" />
    <!--text view for displaying our API response-->
        android:textSize="15sp" />
    <!--progress bar for loading -->
        android:visibility="gone" />

Step 5: Creating a modal class for storing our data  

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as DataModal and add the below code to it. Comments are added inside the code to understand the code in more detail.


public class DataModal {
    // string variables for our name and job
    private String name;
    private String job;
    public DataModal(String name, String job) { = name;
        this.job = job;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getJob() {
        return job;
    public void setJob(String job) {
        this.job = job;

Step 6: Creating an Interface class for our API Call

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class 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.


import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface RetrofitAPI {
    // as we are making a post request to post a data
    // so we are annotating it with post
    // and along with that we are passing a parameter as users
    //on below line we are creating a method to post our data.
    Call<DataModal> createPost(@Body DataModal dataModal);

Step 7: Working with the file

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


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
    // creating variables for our edittext, 
    // button, textview and progressbar.
    private EditText nameEdt, jobEdt;
    private Button postDataBtn;
    private TextView responseTV;
    private ProgressBar loadingPB;
    protected void onCreate(Bundle savedInstanceState) {
        // initializing our views
        nameEdt = findViewById(;
        jobEdt = findViewById(;
        postDataBtn = findViewById(;
        responseTV = findViewById(;
        loadingPB = findViewById(;
        // adding on click listener to our button.
        postDataBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // validating if the text field is empty or not.
                if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter both the values", Toast.LENGTH_SHORT).show();
                // calling a method to post the data and passing our name and job.
                postData(nameEdt.getText().toString(), jobEdt.getText().toString());
    private void postData(String name, String job) {
        // below line is for displaying our progress bar.
        // on below line we are creating a retrofit 
        // builder and passing our base url
        Retrofit retrofit = new Retrofit.Builder()
                // as we are sending data in json format so 
                // we have to add Gson converter factory
                // at last we are building our retrofit builder.
        // below line is to create an instance for our retrofit api class.
        RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
        // passing data from our text fields to our modal class.
        DataModal modal = new DataModal(name, job);
        // calling a method to create a post and passing our modal class.
        Call<DataModal> call = retrofitAPI.createPost(modal);
        // on below line we are executing our method.
        call.enqueue(new Callback<DataModal>() {
            public void onResponse(Call<DataModal> call, Response<DataModal> response) {
                // this method is called when we get response from our api.
                Toast.makeText(MainActivity.this, "Data added to API", Toast.LENGTH_SHORT).show();
                // below line is for hiding our progress bar.
                // on below line we are setting empty text
                // to our both edit text.
                // we are getting response from our body 
                // and passing it to our modal class.
                DataModal responseFromAPI = response.body();
                // on below line we are getting our data from modal class and adding it to our string.
                String responseString = "Response Code : " + response.code() + "\nName : " + responseFromAPI.getName() + "\n" + "Job : " + responseFromAPI.getJob();
                // below line we are setting our 
                // string to our text view.
            public void onFailure(Call<DataModal> call, Throwable t) {
                // setting text to our text view when 
                // we get error response from API.
                responseTV.setText("Error found is : " + t.getMessage());

Now run your app and see the output of the app. 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 Feb, 2021
Like Article
Save Article
Similar Reads
Related Tutorials