Africa\'s Talking
Android Consuming REST API with Kotlin.

Consuming REST API with Kotlin.

-

- Advertisment -

Being an android developer, at some point, you will encounter the term REST API during development. Well, what does this term mean? Let us break it down, REST is an acronym for Representational State Transfer, this is a mode of communication between two computers over HTTP. In our case, the two computers are an android device and a remote server.

Enough about definitions, today we are going to connect the two “computers”.  Let’s get started by opening android studio, click on start a new Android Studio Project .

Next, we will select an Empty Activity template.

Great, now let us name our project. Under the Name title, rest demo will be our project name. Click  finish  and wait for android studio to load the project.

Once our project is ready, install the following dependencies retrofit2 and okhttp in our build.gradle(Module:app) file.

Add dependencies and sync the project.

dependencies {

implementation'com.squareup.retrofit2:retrofit:2.1.0'
implementation'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation'com.squareup.okhttp3:okhttp:3.14.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'

}
build.gradle(Module:app)

The logging-interceptor will display the API response in the log as a string.

The Gson library will aid in converting the JSON response to the intended type.

Add internet permissions in the manifest file.

<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testdemo">
<uses-permission android:name="android.permission. INTERNET"/>

manifest.xml

Retrofit instance

Create a new file named apiclient. The class ApiClient will always be called when making any API calls. This file will contain our base url to our RESTful API and instantiate our refrofit and okhttp libraries.

object ApiClient {

//enter your base url here
var BASE_URL:String="https://"

val getClient: ApiInterface
   get() {
     val gson = GsonBuilder()
        .setLenient()
        .create()

     val interceptor = HttpLoggingInterceptor()
     interceptor.apply {
     interceptor.level =
     HttpLoggingInterceptor.Level.BODY

     val client = OkHttpClient.Builder().build()

     val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)

.addConverterFactory(GsonConverterFactory.create(gson))
        .build()

     return retrofit.create(ApiInterface::class.java)
   }
}
apiclient.kt

Create an interface

interface APiInterface{

@GET("/api/user")fun getUser(@Header("authorization")
header:String):Call<RestDataModel>

@POST("/api/users/accounts")
@FormUrlEncoded
fun postUser(@Field("uname") username:String,
@Field("firstname")first_name:String,
@Field("secondname")second_name:String):Call<RestDataModel>

}
interface

From our interface, the annotation @POST sends data to our server and @GET retrieves our data. @Field annotation sends form-url encoded data and it’s only used when posting data.

The functions getUser() and postUser() will be accessed in main activity where the fields username, firstname and second name will be passed to them. These functions extend the model class RestDataModel that helps parsing the data to and from the server.

Create a model class

The model class helps our Gson converter to parse the data we obtain from or to our server. Create a new class file named RestModel and paste the following code.

data class RestDataModel (

@Expose
@SerializedName("firstname") val first_name :String,

@Expose
@SerializedName("secondname") val second_name :String,

@Expose
@SerializedName("uname") val user_name :String)
RestModel.kt

The annotation @SerializedName is the actual variable name in the JSON response which will be returned while the val defined will be our guide to knowing the returned type of data in the JSON object.

Make the REST API call

In our main activity, we shall make our first call.

val call: Call<RestDataModel> =
ApiClient.getClient.postUser("username","firstname","secondname")
  call.enqueue(object :Callback<RestDataModel> {

  override fun onResponse(call: Call<RestDataModel>?,
response:Response<RestDataModel>?) {

    if(response!!.isSuccessful){
       Log.d("response","${response.body()!!}")
    }
  }

  override fun onFailure(call: Call<RestDataModel>?, t:
Throwable?) {
       Log.d("api error","$t")
  }
})
MainActivity.kt

The variable call instantiates retrofit and makes an API endpoint call for instance the postUser which takes parameters username, firstname and secondname.

We then call method enqueue with two override methods. When we run app either a response or an error will be logged. Android studio will automatically import the interface and model class. If this fails, don’t worry hover your mouse on the underlined red text press alt and enter.

May The Code Be With You.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Posts

Building Application using Node.js HTTPS Module and Africa’s Talking SMS API

Introduction For a long time, HTTP (Hypertext Transfer Protocol) was responsible for communication between a client application and a server...

Building an Exam Enrollment and Grade Notification System using Africa’s Talking SMS Shortcode API in Django

Introduction This article explores the application of SMS shortcodes to create transparency and improve the quality of education in learning...

Build a user account management system using USSD and SMS API in Go

Introduction We will be learning how to use both the Africastalking SMS and USSD api by building an application where...

Date & Time Analysis With R

One will learn how to analyse dates and time; reproducing date-related columns from a date and also format dates and time. In application, one will learn how to plot simple and multiple time series data using the R language.
- Advertisement -

Two Factor Authentication With PHP and Africa’s Talking SMS API

Two factor authentication is an additional layer of security used to ensure only authenticated users gain access to an online account. because Passwords are historically weak, and can be easily stolen, it can't alone be the way that users access their accounts.

Building a masked number system using Spring Boot, Android and Voice Apis from Africa’s Talking

Introduction In this walk through we shall be building a platform to enable a hypothetical company have their agents call...
- Advertisement -

You might also likeRELATED
Recommended to you