How to call rest API in android using Retrofit

How to call rest API in android using Retrofit

In this tutorial, we will learn about the Retrofit client and learn how to call rest API in android using Retrofit. As we know Retrofit client is used to calling the third-party APIs from our android application. To integrate Retrofit into our android application we have to follow the below steps:

Permissions For Calling APIs

  1. Add the INTERNET permission inside the AndroidManifest.xml file. Without this permission, we can’t call the APIs.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

If we are calling remote APIs than its fine then you don’t need to add this android:usesCleartextTraffic property, but If we try to call the API from our localhost then android don’t allow us. So if we want to call the localhost API than instead of localhost we have to use the IP address of our network and also we have to add the below line in our AndroidManifest.xml inside the application tag.

android:usesCleartextTraffic="true"

To get your IP address open your cmd and type ipconfig command and copy the IP address from there. So if your localhost API is like

http://localhost:8080/test  
then it will become
http://192.168.1.5:8080/test

Steps to use Retrofit

2. Add the Retrofit client dependency in our app gradle file.

implementation 'com.squareup.retrofit2:retrofit:2.7.2'
implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
implementation 'com.squareup.okhttp3:okhttp:3.6.0'
3. First We will create the design inside our activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textColor="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.022" />

    <Button
        android:id="@+id/getRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get"
        tools:layout_editor_absoluteX="148dp"
        tools:layout_editor_absoluteY="64dp" />


    <EditText
        android:id="@+id/editText"
        android:layout_width="326dp"
        android:layout_height="39dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Write Here for Request"
        tools:layout_editor_absoluteX="42dp"
        tools:layout_editor_absoluteY="383dp" />

    <Button
        android:id="@+id/getPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Path Variable"
        tools:layout_editor_absoluteX="117dp"
        tools:layout_editor_absoluteY="139dp" />

    <Button
        android:id="@+id/getQuery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Query Param"
        tools:layout_editor_absoluteX="128dp"
        tools:layout_editor_absoluteY="200dp" />

    <Button
        android:id="@+id/getPathAndQuery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get With Path and Query"
        tools:layout_editor_absoluteX="95dp"
        tools:layout_editor_absoluteY="274dp" />

    <Button
        android:id="@+id/post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post"
        tools:layout_editor_absoluteX="166dp"
        tools:layout_editor_absoluteY="445dp" />


</LinearLayout>

So our app design will look like below

Spring boot API in android

4. Now we have to define the endpoints that we want to call from our android application. While using retrofit we define these endpoints inside the interface. So create an interface and put the below code there.

package com.example.retorfitapiexample;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface RetroApis {

    // As we are calling localhost APIs so we change localhost with the IP my actual localhost API is http://localhost:8080/
    String BASE_URL = "http://192.168.1.5:8080/";

    //calling URL = http://localhost:8080/test
    @GET("test")
    Call<Object> getTestData();

    //calling URL = http://localhost:8080/test/123
    @GET("test/{id}")
    Call<Object> getPathVariableData(@Path("id") String id);

    //calling URL = http://localhost:8080/queryTest?queryParam=vasu
    @GET("queryTest")
    Call<Object> getQueryParamData(@Query("queryParam") String queryParam);

    //calling URL = http://localhost:8080/queryTest/123?queryParam=vasu
    @GET("queryTest/{id}")
    Call<Object> getWithQueryAndParamVarTest(@Path("id") String id, @Query("queryParam") String queryParam);

    //calling URL = http://localhost:8080/postTest
    @POST("postTest")
    Call<Object> getPostData(@Body String body);
}

5. Now we have to create a class that is used to get the instance of Retrofit. Here we are creating a Singleton class so we only get the one instance of Retrofit for each call. We create a class and inside it’s default constructor we create the instance of Retrofit. So create a class with any name and put the below code there as we are creating a class with name MyRetrofitClient.java so our class will look like below:

package com.example.retorfitapiexample;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyRetrofitClient {

    private static MyRetrofitClient myRetrofitClient = null;
    private static RetroApis myRetroApis;

    private MyRetrofitClient() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(myRetroApis.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        myRetroApis = retrofit.create(RetroApis.class);
    }

    public static synchronized MyRetrofitClient getInstance() {
        if (myRetrofitClient == null) {
            myRetrofitClient = new MyRetrofitClient();
        }
        return myRetrofitClient;
    }

    public RetroApis getMyApi() {
        return myRetroApis;
    }
}

6. Code For MainActivity.java

So now time come for writing our main class Code. Now open your MainActivity.java class and initialize all the View widget like text View, edit Text and buttons. we have implemented View.OnClickListener interface and override it’s onClick method in our MainActivity.java. Now our MainActivity.java class look like below:

package com.example.retorfitapiexample;

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 okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView textView;
    EditText editText;
    Button getRequestButton;
    Button getRequestWithPathVariableButton;
    Button getRequestWithQueryParamButton;
    Button getRequestWithPathVarAndQueryParamButton;
    Button postRequestButton;

    private static final String EMPTY_STRING = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);

        getRequestButton = (Button) findViewById(R.id.getRequest);
        getRequestWithPathVariableButton = (Button) findViewById(R.id.getPath);
        getRequestWithQueryParamButton = (Button) findViewById(R.id.getQuery);
        getRequestWithPathVarAndQueryParamButton = (Button) findViewById(R.id.getPathAndQuery);
        postRequestButton = (Button) findViewById(R.id.post);

        getRequestButton.setOnClickListener(this);
        getRequestWithPathVariableButton.setOnClickListener(this);
        getRequestWithQueryParamButton.setOnClickListener(this);
        getRequestWithPathVarAndQueryParamButton.setOnClickListener(this);
        postRequestButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.getRequest:
                getApiDataWithParamORPostData("");
                break;
            case R.id.getPath:
                getApiDataWithParamORPostData("path");
                break;
            case R.id.getQuery:
                getApiDataWithParamORPostData("query");
                break;
            case R.id.getPathAndQuery:
                getApiDataWithParamORPostData("queryAndPath");
                break;
            case R.id.post:
                getApiDataWithParamORPostData("post");
                break;
        }
    }

    private void getApiDataWithParamORPostData(String callType) {
        try {
            Call<Object> call = null;

            if (callType.equals("")) {
                call = MyRetrofitClient.getInstance().getMyApi().getTestData();
            } else if (callType.equals("path")) {
                call = MyRetrofitClient.getInstance().getMyApi().getPathVariableData(editText.getText().toString());
            } else if (callType.equals("query")) {
                call = MyRetrofitClient.getInstance().getMyApi().getQueryParamData(editText.getText().toString());
            } else if (callType.equals("queryAndPath")) {
                call = MyRetrofitClient.getInstance().getMyApi().getWithQueryAndParamVarTest(editText.getText().toString(), editText.getText().toString());
            } else if (callType.equals("post")) {
                call = MyRetrofitClient.getInstance().getMyApi().getPostData(editText.getText().toString());
            }

            call.enqueue(new Callback<Object>() {
                @Override
                public void onResponse(Call<Object> call, Response<Object> response) {
                    textView.setText(response.body().toString());
                }

                @Override
                public void onFailure(Call<Object> call, Throwable t) {
                    textView.setText("Api Call Failed" + t.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            textView.setText("Some Exception Occurred in Api CAll");
        }
    }


}
Result of Application

Now We are done Just run your application and see the result.

Spring Boot APIs

As You know we are using local APIs that we have created with the spring boot framework. If you have your APIS to call then you can ignore this section but if you want to create local APIs to test your application then follow the below steps:

Create a Spring boot Project and put the below dependency in your pom.xml file:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
 <scope>runtime</scope>
 <optional>true</optional>
</dependency>

<dependency>
 <groupId>org.json</groupId>
 <artifactId>json</artifactId>
 <version>20210307</version>
</dependency>

pom.xml

Spring Boot Controller for APIs

Now create a controller class and create the GET and POST APIs there. So just create a simple java class annotate that class with @RestController. And Now create method with @GetMapping to create GET APIs and @PostMapping to create POST APIs. So Now your Spring boot controller is look like below:

package com.javadream;

import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class APis {

	JSONObject jobj = new JSONObject();

	// URL = http://localhost:8080/test
	@GetMapping("test")
	public String test() {
		jobj.clear();
		jobj.put("requestType", "GET Request");
		return jobj.toString();
	}

	// URL = http://localhost:8080/test/123
	@GetMapping("/test/{id}")
	public String pathVariableTest(@PathVariable String id) {
		jobj.clear();
		jobj.put("requestType", "GET with Path Variable");
		jobj.put("pathVariable", id);
		return jobj.toString();
	}

	// URL = http://localhost:8080/queryTest?queryParam=vasu
	@GetMapping("/queryTest")
	public String queryParamTest(@RequestParam String queryParam) {
		jobj.clear();
		jobj.put("requestType", "GET with Query Param");
		jobj.put("QueryParam", queryParam);
		return jobj.toString();
	}

	//URL = http://localhost:8080/queryTest/123?queryParam=vasu
	@GetMapping("/queryTest/{id}")
	public String queryParamAndPathVarTest(@PathVariable String id, @RequestParam String queryParam) {
		jobj.clear();
		jobj.put("requestType", "GET with Query Param And Path Variable");
		jobj.put("QueryParam", queryParam);
		jobj.put("pathVariable", id);
		return jobj.toString();
	}
	
	@PostMapping("/postTest")
	public String test(@RequestBody String data) {
		jobj.clear();
		jobj.put("requestType", "Post Request");
		jobj.put("payload", data);
		return jobj.toString();
	}

}

Now run your Spring boot application and text your APIs. These are the same APIs that we are calling from our android project.

Download Code

So let’s download the code from Github.

Download Retrofit client code for Android

Download Spring Boot APIs Project

Other Posts you may like

So it’s the end of the tutorial, So if you reached here means you have successfully learned how to call rest API in android using Retrofit. There is some other post that you make like:

On delete and On Update cascading in MySQL complete example

Send SMS to any mobile number in the world using Twilio

Help Others, Please Share

Leave a Reply

Your email address will not be published. Required fields are marked *

x