Open In App

How to GET Data From API using Retrofit Library in Android?

Last Updated : 14 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A GET request is one of the HTTP request methods that can be used to retrieve data from a server. In an API context, a GET request is typically used to retrieve a specific resource or a collection of resources from a server. When a client makes a GET request to a server, it sends a request message that contains the URL of the desired resource along with any optional query parameters. The server then responds with a response message that contains the requested data, typically in the form of a JSON or XML document.

In this article we are going to see how can we GET data from an API using the Retrofit library, for this we have to follow some steps :

  1. Define a data model that represents the response data you expect to receive from the API endpoint.
  2. Define an interface that describes the API endpoints you want to access. This interface should include one or more methods that specify the HTTP method (e.g. GET), the endpoint URL, and any query parameters 
  3. Use Retrofit to create an implementation of your API interface. This implementation will handle making HTTP requests and parsing the response data.
  4. Call the desired method on the implementation to initiate the HTTP request. You can use the enqueue() method to execute the request asynchronously and receive the response data in a callback function.

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 and select the language as Kotlin

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. 

// Add theese two Dependency
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

After adding you need to sync your project.

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. 

XML




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


Step 4: Change the StatusBar Color

Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.

<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>

Step 5: 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




<?xml version="1.0" encoding="utf-8"?>
<!--LinearLayout Vertical-->
<LinearLayout 
    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">
      
      <!--Button-->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_joke"
        android:text="Get Joke" />
    
    <!--TextView-->
    <TextView
       android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Jokes : "
        android:textColor="@color/black"
        android:textStyle="bold"
        android:textSize="15dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
    <!--TextView-->
    <TextView
        android:layout_margin="10dp"
        android:id="@+id/tv_joke"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textColor="@color/black"
        android:textStyle="bold"
        android:textSize="15dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
    <!--progress bar for loading -->
    <ProgressBar
        android:id="@+id/idLoadingPB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />
  
</LinearLayout>


Step 6: Creating a Model Class for our jokes  

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

Kotlin




package com.example.gfg
  
// Model class for our Jokes 
data class DataModel(
    var categoories:ArrayList<String>,
    var created_at: String,
    var icon_url:String,
    var id:String,
    var updated_at:String,
    var url:String,
    var value:String
):java.io.Serializable


Step 7: Creating an Interface class for our API

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

Kotlin




package com.example.gfg
  
import retrofit.Call
import retrofit.http.GET
  
// This interface defines an API 
// service for getting random jokes.
interface ApiService {
    // This annotation specifies that the HTTP method
    // is GET and the endpoint URL is "jokes/random".
    @GET("jokes/random")
    // This method returns a Call object with a generic 
    // type of DataModel, which represents 
    // the data model for the response.
    fun getjokes(): Call<DataModel>
  
}


Step 8: Create a class for handling API Calls

Navigate to the app > java > your app’s package name > Right-click on it > New > class and name the file as APiCall and add the below code to it. Comments are added inside the code to understand the code in more detail. In this call, we are going to make a Get request to our API using the Retrofit library.

Kotlin




package com.example.gfg
  
import android.content.Context
import android.provider.ContactsContract.Data
import android.widget.Toast
import retrofit.*
  
class ApiCall {
    // This function takes a Context and callback function
    // as a parameter, which will be called
    // when the API response is received.
    fun getjokes(context: Context, callback: (DataModel) -> Unit) {
  
        // Create a Retrofit instance with the base URL and 
        // a GsonConverterFactory for parsing the response.
        val retrofit: Retrofit = Retrofit.Builder().baseUrl("https://api.chucknorris.io/").addConverterFactory(
            GsonConverterFactory.create()).build()
  
        // Create an ApiService instance from the Retrofit instance.
        val service: ApiService = retrofit.create<ApiService>(ApiService::class.java)
  
        // Call the getjokes() method of the ApiService 
        // to make an API request.
        val call: Call<DataModel> = service.getjokes()
  
        // Use the enqueue() method of the Call object to
        // make an asynchronous API request.
        call.enqueue(object : Callback<DataModel> {
            // This is an anonymous inner class that implements the Callback interface.
            override fun onResponse(response: Response<DataModel>?, retrofit: Retrofit?) {
            // This method is called when the API response is received successfully.
  
                if(response!!.isSuccess){
                    // If the response is successful, parse the 
                    // response body to a DataModel object.
                    val jokes: DataModel = response.body() as DataModel
                      
                    // Call the callback function with the DataModel
                    // object as a parameter.
                    callback(jokes)
                }
            }
  
            override fun onFailure(t: Throwable?) {
                // This method is called when the API request fails.
                Toast.makeText(context, "Request Fail", Toast.LENGTH_SHORT).show()
            }
        })
    }
}


Step 9: Working with the MainActivity.kt file

Go to the MainActivity.kt and follow the below code. Below is the code for the MainActivity.kt. Comments are added inside the code to understand the code in more detail. In this mainly we are going to call the ApiCall class getjokes() method.

Kotlin




package com.example.gfg
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
  
class MainActivity : AppCompatActivity() {
  
    private lateinit var btn_jokes: Button
    private lateinit var tv_jokes: TextView
    private lateinit var progressBar: ProgressBar
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          
        // Find the button view by its ID and
        // assign it to a variable.
        btn_jokes = findViewById(R.id.btn_joke)
          
        // Find the text view by its ID and
        // assign it to a variable.
        tv_jokes = findViewById(R.id.tv_joke)
          
        // Find the progress bar and assign
        // it to the varriable.
        progressBar = findViewById(R.id.idLoadingPB)
          
        // Set an OnClickListener on the button view.
        btn_jokes.setOnClickListener {
            // show the progress bar
            progressBar.visibility = View.VISIBLE 
            
            // Call the getjokes() method of the ApiCall class, 
            // passing a callback function as a parameter.
            ApiCall().getjokes(this) { jokes ->
                // Set the text of the text view to the 
                // joke value returned by the API response.
                tv_jokes.text = jokes.value
                  // hide the progress bar
                progressBar.visibility = View.GONE 
            }
        }
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads