How to GET Data From API using Retrofit Library in Android?
Last Updated :
14 May, 2023
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 :
- Define a data model that represents the response data you expect to receive from the API endpoint.
- 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
- Use Retrofit to create an implementation of your API interface. This implementation will handle making HTTP requests and parsing the response data.
- 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
< 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
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:gravity = "center"
tools:context = ".MainActivity" >
< Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/btn_joke"
android:text = "Get Joke" />
< 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
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" />
< 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
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
interface ApiService {
@GET ( "jokes/random" )
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 {
fun getjokes(context: Context, callback: (DataModel) -> Unit) {
GsonConverterFactory.create()).build()
val service: ApiService = retrofit.create<ApiService>(ApiService:: class .java)
val call: Call<DataModel> = service.getjokes()
call.enqueue(object : Callback<DataModel> {
override fun onResponse(response: Response<DataModel>?, retrofit: Retrofit?) {
if (response!!.isSuccess){
val jokes: DataModel = response.body() as DataModel
callback(jokes)
}
}
override fun onFailure(t: Throwable?) {
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)
btn_jokes = findViewById(R.id.btn_joke)
tv_jokes = findViewById(R.id.tv_joke)
progressBar = findViewById(R.id.idLoadingPB)
btn_jokes.setOnClickListener {
progressBar.visibility = View.VISIBLE
ApiCall().getjokes( this ) { jokes ->
tv_jokes.text = jokes.value
progressBar.visibility = View.GONE
}
}
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...