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 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 instanciate 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. This 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 instanciates 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.

You've successfully subscribed to Decoded For Devs
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Your link has expired
Success! Your account is fully activated, you now have access to all content.