Call POST API In Android Using Retrofit

Introduction

Retrofit is a Java and Android HTTP networking library that is type-safe. Since Retrofit was so quick, had better capabilities, and even easier syntax, it was even better. Since then, the majority of developers have shifted to using Retrofit to submit API requests.

Retrofit requires at least Java 8+ or Android API 21+.

POST is a method for sending information to a server to add or update resources.

The data sent to the server with POST API is stored in the request body of the request.

So, in this article, we will learn how to Call POST API in Android Using Retrofit.

Using Retrofit, call the POST API in Android

Step 1

Create a new project in the Android Studio and select an empty activity.

Call POST API in Android Using Retrofit

Step 2

Give the project a name, select the save location folder, and click on the finish button.

Call POST API in Android Using Retrofit

Step 3

Add the following dependencies to your app-level build.gradle file.

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Step 4

Create a class for RetrofitInstance with the name RetrofitClient.java.

package com.uday.retrofitpostdemo;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
    private static Retrofit retrofit;
    private static String BASE_URL = "https://reqres.in/";
    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
}

Here we use a sample API from reqres.in

Sample API request and response as follows:

Sample Request Body

{
    "name": "morpheus",
    "job": "leader"
}

Sample Response Body

{
    "name": "morpheus",
    "job": "leader",
    "id": "469",
    "createdAt": "2022-11-22T04:31:00.355Z"
}

Step 5

Based on the above response, create a Model class with the name Model.java to store API responses and also create its constructor and its getter methods. For request body don't create its classs we directly pass in method arguments using @Field And @FormUrlEncoded.

package com.uday.retrofitpostdemo;

public class Model {
    private String name;
    private String job;
    private String id;
    private String createdAt;

    public Model(String name, String job, String id, String createdAt) {
        this.name = name;
        this.job = job;
        this.id = id;
        this.createdAt = createdAt;
    }

    public String getName() {
        return name;
    }

    public String getJob() {
        return job;
    }

    public String getId() {
        return id;
    }

    public String getCreatedAt() {
        return createdAt;
    }
}

Step 6

Create an interface to declare a method that calls an API with the name Methods.java.

package com.uday.retrofitpostdemo;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface Methods {

    @FormUrlEncoded
    @POST("/api/users")
    Call<Model> getUserData(@Field("name")String name,@Field("job") String job);
}

Step 7

Create the activity_main.xml file as shown below.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="vertical"
        tools:ignore="MissingConstraints"
        android:gravity="center">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp"
            android:layout_marginTop="50dp"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:textSize="20dp"
            android:hint="Enter Name"
            android:id="@+id/txtName" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="20dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:textSize="20dp"
            android:hint="Enter Job"
            android:id="@+id/txtJob"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send POST Request"
            android:layout_marginTop="20dp"
            android:textSize="20dp"
            android:id="@+id/btnPostData"
            android:layout_gravity="center" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:padding="20dp"
            android:layout_marginTop="20dp"
            android:textSize="20dp"
            android:text=": Output :"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:padding="10dp"
            android:layout_marginTop="10dp"
            android:textSize="20dp"
            android:text=""
            android:id="@+id/lblOutput"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 8

Declare button objects and edittext objects and Textview objects in the MainActivity.java class.

private EditText txtName,txtJob;
private TextView lblOutput;
private Button btnPostData;

Step 9

Add listeners to the "Send Post Request" button and add code for calling the API and, after getting the response, setting that data to the textview.

 btnPostData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Get Data From TextBox
                String strName,strJob;
                strName = txtName.getText().toString();
                strJob = txtJob.getText().toString();

                if(strName == "")
                {
                    Toast.makeText(MainActivity.this,"Please Enter Name",Toast.LENGTH_SHORT).show();
                }
                else if(strJob == "")
                {
                    Toast.makeText(MainActivity.this,"Please Enter Job",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Methods methods = RetrofitClient.getRetrofitInstance().create(Methods.class);
                    Call<Model> call = methods.getUserData(strName,strJob);

                    call.enqueue(new Callback<Model>() {
                        @Override
                        public void onResponse(Call<Model> call, Response<Model> response) {
                              String strOutput = "";
                              strOutput =  "Id : " + response.body().getId();
                              strOutput = strOutput + "\nName : " + response.body().getName();
                              strOutput = strOutput + "\nJob : " + response.body().getJob();
                              strOutput = strOutput + "\nCreated At : " + response.body().getCreatedAt();
                              lblOutput.setText(strOutput);
                        }

                        @Override
                        public void onFailure(Call<Model> call, Throwable t) {
                            Toast.makeText(MainActivity.this,"Error Occurred",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

Step 10

Include Internet Permission in the manifest file. 

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

Final MainActivity.Java File

package com.uday.retrofitpostdemo;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private EditText txtName,txtJob;
    private TextView lblOutput;
    private Button btnPostData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtName = findViewById(R.id.txtName);
        txtJob = findViewById(R.id.txtJob);
        lblOutput = findViewById(R.id.lblOutput);
        btnPostData = findViewById(R.id.btnPostData);


        btnPostData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Get Data From TextBox
                String strName,strJob;
                strName = txtName.getText().toString();
                strJob = txtJob.getText().toString();

                if(strName == "")
                {
                    Toast.makeText(MainActivity.this,"Please Enter Name",Toast.LENGTH_SHORT).show();
                }
                else if(strJob == "")
                {
                    Toast.makeText(MainActivity.this,"Please Enter Job",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Methods methods = RetrofitClient.getRetrofitInstance().create(Methods.class);
                    Call<Model> call = methods.getUserData(strName,strJob);

                    call.enqueue(new Callback<Model>() {
                        @Override
                        public void onResponse(Call<Model> call, Response<Model> response) {
                              String strOutput = "";
                              strOutput =  "Id : " + response.body().getId();
                              strOutput = strOutput + "\nName : " + response.body().getName();
                              strOutput = strOutput + "\nJob : " + response.body().getJob();
                              strOutput = strOutput + "\nCreated At : " + response.body().getCreatedAt();
                              lblOutput.setText(strOutput);
                        }

                        @Override
                        public void onFailure(Call<Model> call, Throwable t) {
                            Toast.makeText(MainActivity.this,"Error Occurred",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

    }
}

Step 11

Now run your app.

Call POST API in Android Using Retrofit

Step 12

Now insert the data in the textbox and then click on the "Send Post Request Button" and you see the following output.

Call POST API in Android Using Retrofit

Summary

So you see, it's very easy to call the POST API in Android using Retrofit.

In this article, we have learned about how to call the POST API in Android using Retrofit.

If you want to learn How to Call GET API in Android Using Retrofit then click here

Thank you. Enjoy Coding.


Similar Articles