Consuming REST API with Kotlin.
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
Add dependencies and sync the project.
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.
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
Create an 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.
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.
@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.
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
May The Code Be With You.