Get request retrofit

GET request using retrofit in Android Tutorial

In this tutorial, we will learn about retrofit and making a GET request using the retrofit library, we will implement Glide Library also for image loading. Retrofit is the most amazing library for android that seamlessly handles all the HTTP requests and responses.

Retrofit is a REST Client for Java and Android developed by Square Inc under the Apache 2.0 license. It is a straightforward network library that is used for network transactions. We can capture JSON responses from web services/web APIs using this library. It is a simple and quick library for retrieving and uploading data (JSON or other structured data) via a REST-based web service.


Retrofit classes

  • Model class – The objects to be obtained from the JSON file are stored in this class.
  • Retrofit instance – This Java class is used to make API requests.
  • The interface class in Java is used to define endpoints.
Pros of Retrofit Cons of Retrofit
It is extremely fast.
It allows you to communicate directly with the web service.
It is simple to use and comprehend.
It accepts post requests as well as multipart uploads.
It is capable of handling both synchronous and asynchronous network requests.
It does not support the loading of images. It necessitates the use of additional libraries such as Glide and Picasso.
It does not allow you to set priorities.

What is Glide?

Glide is an Image Loader Library for Android developed by bumptech and is a Google-recommended library. It’s been used in a number of Google open-source projects. It supports animated GIFs and handles image loading/caching.

Glide is an open-source media management and image loading framework for Android that wraps media decoding, memory and disc caching, and resource pooling into a simple and easy-to-use interface.


You should know the basic knowledge of android apps, folder structures, debugging, and running applications.


  • To get the most recent news, you’ll need to use a third-party API.
  • Retrofit library is required to call that API.
  • Call the API, get the response, and store it in RecyclerView.
  • A glide library is required for Image loading.

In this example, I’m using the site to get the API(Free).
To use this API, we need an API KEY, which we can obtain by registering at
you will receive an API KEY after a successful registration.

We should call the API given below using this API Key.

Let’s begin with an Android Studio.

  • Open Android Studio and create a new Android project.
  • Open the build.gradle(app) file
  • In this project, we will use Retrofit to call the API.
  • Use RecyclerView to display the Response list.
  • In this project, we will use the Glide library for image loading.


    //Glide library dependency
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'

    //recycler view dependency
    implementation "androidx.recyclerview:recyclerview:1.2.1"

    // retrofit library dependency
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.0'

Because we work with network operations and other such things, we require Internet connection permission.
As a result, we must include Internet permission in AndroidManifest.xml.

//Internet Permission

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

Below is the code of the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

    <uses-permission android:name="android.permission.INTERNET" />
        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


In general, we require 3 classes to use the retrofit library –

  • Retrofit Builder Class: Build a retrofit instance that sends any HTTP request.
  • Model class: JSON representation in java.
  • The interface class in Java is used to define endpoints.

Create an instance of Retrofit

To send a request to the API, we must first create a retrofit instance. So, in the rest package, create a class called NewsService and write the code given below to create a retrofit instance. When creating an instance, we must specify the base URL for all requests. The base URL, in this case, is “”.

package com.sagar.retrofitexample

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query

const val BASE_URL = ""
const val API_KEY = "Place your API KEY here"

interface NewsInterface {
    fun getHeadline(@Query("country") country: String, @Query("page") page: Int) : Call<News>

object NewsService{
    val newsInstance: NewsInterface
    init {
        val retrofit= Retrofit.Builder()
        newsInstance = retrofit.create(

The Converter dependency includes a GsonConverterFactory class. Then invoke the class creates instance method. It is accomplished by calling create() on our retrofit instance and invoking the addConverterFactory method ().
It will automatically map JSON data to your Java Object.

Create Model class

We need to know what the model class’s content will be before we create it. In Java, the Model class represents JSON. As a result, we must understand the contents of JSON. The JSON URL that we will be using in this tutorial is
  • Create a News data class by observing the response.
package com.sagar.retrofitexample

data class News(val totalResult: Int, val articles: List<Article>)
  • Now Create Article data class
package com.sagar.retrofitexample

data class Article(val author:String, val title: String, val description: String, val url: String, val urlToImage: String)

Adding RecyclerView into XML file

Because we saved the result in a RecyclerView, we need to create a RecyclerView. To do so, we must first declare it in activity main.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=""

        app:layout_constraintTop_toTopOf="parent" />


Create an item for recyclerView

To use the android retrofit library with the recyclerView, we must first define a layout for an item in the recyclerView.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android=""


            tools:srcCompat="@tools:sample/avatars" />

            android:text="TextView" />


            android:text="TextView" />

Create a RecyclerView Adapter

We have completed some basic setups to use the android retrofit library with recyclerView. We will now create an adapter that will provide data to the recyclerView. Now we must create an adapter class for RecyclerView.

package com.sagar.retrofitexample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class NewsAdapter(val context: Context, val articles: List<Article>) :
    RecyclerView.Adapter<NewsAdapter.ArticleViewHolder>() {

    class ArticleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var newsImage = itemView.findViewById<ImageView>(
        var newsTitle = itemView.findViewById<TextView>(
        var newsDescription = itemView.findViewById<TextView>(

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.news_item, parent, false)
        return ArticleViewHolder(view)

    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
        val article = articles[position]
        holder.newsTitle.text = article.title
        holder.newsDescription.text = article.description
        holder.itemView.setOnClickListener {

    override fun getItemCount(): Int {
        return articles.size

We defined three methods in the RecyclerView Adapter class (onCreateViewHolder(), onBindViewHolder(), and getItemCount()).

  • onCreateViewHolder() method – Creates an item view
  • onBindViewHolder() method – Binds data for a view
  • getItemCount() method – Returns the total number of items in the list

Make a GET request/ Make an HTTP request with the Retrofit Library.

So far, we’ve successfully created an adapter, an API service, a model class instance, and UI, items in recyclerView. Now we’ll look at how to make an HTTP request with the retrofit library.
Using the retrofit library, we can send GET, PUT, POST, PATCH, and DELETE requests. In this android application, we will now make an HTTP request using the retrofit library.

We’ll use retrofit to make a GET request that returns all data.

Finally, if the information is not successfully loaded into the RecyclerView, we will have an onFailure method that will display a Toast message.

Insert the following code into your MainActivity.

package com.sagar.retrofitexample

import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {
    lateinit var adapter: NewsAdapter
    override fun onCreate(savedInstanceState: Bundle?) {


    private fun getData() {

        val news = NewsService.newsInstance.getHeadline("in", 1)
        news.enqueue(object : Callback<News> {
            override fun onResponse(call: Call<News>, response: Response<News>) {
                val news = response.body()
                if (news!= null){
                    adapter = NewsAdapter(this@MainActivity,news.articles)
                    findViewById<RecyclerView>( =adapter
                    findViewById<RecyclerView>( = LinearLayoutManager(this@MainActivity)


            override fun onFailure(call: Call<News>, t: Throwable) {
                Toast.makeText(applicationContext, "Error Occured", Toast.LENGTH_LONG).show();

Run the application now. You will get the output shown in the output section.

  • We hope that this guide will assist you in quickly creating a News Application using the retrofit library in android. We concentrated on making a simple application for this tutorial. If you have any problems, please post them in the comments section, and we will gladly assist you.

This Post Has One Comment

Leave a Reply