Call GET 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+.

GET API is used to requests data from a server.

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

Using Retrofit, call the GET API in Android

Step 1

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

Call GET API in Android Using Retrofit

Step 2

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

Call GET 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.retrofitgetdemo;
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 response as follows:

{
  "page": 1,
  "per_page": 6,
  "total": 12,
  "total_pages": 2,
  "data": [
    {
      "id": 1,
      "email": "[email protected]",
      "first_name": "George",
      "last_name": "Bluth",
      "avatar": "https://reqres.in/img/faces/1-image.jpg"
    },
    {
      "id": 2,
      "email": "[email protected]",
      "first_name": "Janet",
      "last_name": "Weaver",
      "avatar": "https://reqres.in/img/faces/2-image.jpg"
    },
    {
      "id": 3,
      "email": "[email protected]",
      "first_name": "Emma",
      "last_name": "Wong",
      "avatar": "https://reqres.in/img/faces/3-image.jpg"
    },
    {
      "id": 4,
      "email": "[email protected]",
      "first_name": "Eve",
      "last_name": "Holt",
      "avatar": "https://reqres.in/img/faces/4-image.jpg"
    },
    {
      "id": 5,
      "email": "[email protected]",
      "first_name": "Charles",
      "last_name": "Morris",
      "avatar": "https://reqres.in/img/faces/5-image.jpg"
    },
    {
      "id": 6,
      "email": "[email protected]",
      "first_name": "Tracey",
      "last_name": "Ramos",
      "avatar": "https://reqres.in/img/faces/6-image.jpg"
    }
  ]
}

Step 5

Based on the above response, create a Model class with the name Model.java to store API responses and also create its getter and setter methods.

package com.uday.retrofitgetdemo;
import java.util.ArrayList;
public class Model {
    public int page;
    public int per_page;
    public int total;
    public int total_pages;
    public ArrayList < data > data;
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
    public int getPer_page() {
        return per_page;
    }
    public void setPer_page(int per_page) {
        this.per_page = per_page;
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }
    public int getTotal_pages() {
        return total_pages;
    }
    public void setTotal_pages(int total_pages) {
        this.total_pages = total_pages;
    }
    public ArrayList < Model.data > getData() {
        return data;
    }
    public void setData(ArrayList < Model.data > data) {
        this.data = data;
    }
    public class data {
        public int id;
        public String email;
        public String first_name;
        public String last_name;
        public String avatar;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getFirst_name() {
            return first_name;
        }
        public void setFirst_name(String first_name) {
            this.first_name = first_name;
        }
        public String getLast_name() {
            return last_name;
        }
        public void setLast_name(String last_name) {
            this.last_name = last_name;
        }
        public String getAvatar() {
            return avatar;
        }
        public void setAvatar(String avatar) {
            this.avatar = avatar;
        }
    }
}

Step 6

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

package com.uday.retrofitgetdemo;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Methods {
    @GET("api/users?page=1")
    Call<Model> getAllData();
}

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="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:ignore="MissingConstraints">

        <ListView
            android:id="@+id/listviewData"
            android:layout_marginTop="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Get Data From API"
            android:layout_marginTop="20dp"
            android:textSize="20dp"
            android:id="@+id/btnGetData"
            android:layout_gravity="center"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 8

Declare button objects and listview objects in the MainActivity.java class.

private Button btnGetData;
private ListView listView;

Step 9

Add listeners to the "Get Data From Api" button and add code for calling the API and, after getting the response, setting that data to the listview.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnGetData = findViewById(R.id.btnGetData);
    listView = findViewById(R.id.listviewData);
    btnGetData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Methods methods = RetrofitClient.getRetrofitInstance().create(Methods.class);
            Call < Model > call = methods.getAllData();
            call.enqueue(new Callback < Model > () {
                @Override
                public void onResponse(Call < Model > call, Response < Model > response) {
                    ArrayList < Model.data > data = response.body().getData();
                    String[] names = new String[data.size()];
                    for (int i = 0; i < data.size(); i++) {
                        names[i] = "Id : " + data.get(i).getId() + "\nName : " + data.get(i).getFirst_name() + " " + data.get(i).getLast_name() + "\nEmail : " + data.get(i).getEmail();
                    }
                    listView.setAdapter(new ArrayAdapter < String > (getApplicationContext(), android.R.layout.simple_list_item_1, names));
                }
                @Override
                public void onFailure(Call < Model > call, Throwable t) {
                    Toast.makeText(getApplicationContext(), "An error has occured", Toast.LENGTH_LONG).show();
                }
            });
        }
    });
}

Step 10

Include Internet Permission in the manifest file. 

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

Final MainActivity.Java File

package com.uday.retrofitgetdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private Button btnGetData;
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnGetData = findViewById(R.id.btnGetData);
        listView = findViewById(R.id.listviewData);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Methods methods = RetrofitClient.getRetrofitInstance().create(Methods.class);
                Call < Model > call = methods.getAllData();
                call.enqueue(new Callback < Model > () {
                    @Override
                    public void onResponse(Call < Model > call, Response < Model > response) {
                        ArrayList < Model.data > data = response.body().getData();
                        String[] names = new String[data.size()];
                        for (int i = 0; i < data.size(); i++) {
                            names[i] = "Id : " + data.get(i).getId() + "\nName : " + data.get(i).getFirst_name() + " " + data.get(i).getLast_name() + "\nEmail : " + data.get(i).getEmail();
                        }
                        listView.setAdapter(new ArrayAdapter < String > (getApplicationContext(), android.R.layout.simple_list_item_1, names));
                    }
                    @Override
                    public void onFailure(Call < Model > call, Throwable t) {
                        Toast.makeText(getApplicationContext(), "An error has occured", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }
}

Step 11

Now run your app.

Step 12

Click on the "Get Data From API Button" and you see the following output.

Summary

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

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

If you want to learn how to Call POST API in Android Using Retrofit then click here

Thank you. Enjoy Coding.


Similar Articles