Using Retrofit-2 for API Calls

Nandish swarup
Nerd For Tech
Published in
4 min readMay 19, 2021
Photo by Aleks Marinkovic on Unsplash

Retrofit is a type-safe network library that makes android applications easy to consume RESTful web services. It is built by Square and makes it easy to get JSON or XML data which is parsed into Plain Old Java Objects (POJOs).
In simpler language Retrofit is a library that makes our life easier by providing an easy way to make network transactions. It’s very fast and easy to upload or retrieve data from the server via the Rest-based web service.

Retrofit 2 by default leverages OkHttp as the networking layer and is built on top of it.

Retrofit automatically serializes the JSON response using a POJO(Plain Old Java Object) which must be defined in advance for the JSON Structure. To serialize JSON we need a converter to convert it into Gson first.

For Retrofit we need to add the following dependencies to our build.grade file.

  • The logging interceptor generates a log string of the entire response that’s returned.
  • Retrofit 2 by default leverages OkHttp as the networking layer and is built on top of it.
  • To serialize JSON we need a converter to convert it into Gson first

The first step is to create a POJO class that represents data that you want to read from API or send to API.

Let’s suppose we are getting customers information in API and JSON of it looked like this-

So now we have to make a corresponding Pojo class that represents data in this JSON as defined below-

The second step is to create our Interface class which helps in defining our API endpoints with the method

In the above class, we’ve defined some methods that perform HTTP requests with annotation. Other possible lists of annotations for each of the HTTP methods are as follows : @GET, @POST, @PUT, @DELETE, @PATCH or @HEAD.

@GET("api/users") calls getCustomerList();.

getCustomerList() is the method name. CustomerDataModel.java is a Model POJO class for our response object that’s used to map the response parameters to their respective variables. These POJO classes act as the method return type.

Method Parameters: There are a wide variety of possible options of parameters to pass inside a method:

  • @Body – Sends Java objects as a request body.
  • @Url – use dynamic URLs.
  • @Query – We can simply add a method parameter with @Query() and a query parameter name, describing the type. To URL encode a query use the form:
    @Query(value = "auth_token",encoded = true) auth_token:String
  • @Field – send data as form-urlencoded. This requires an @FormUrlEncoded annotation attached with the method.
    The @Field parameter works only with a POST

The third step is to create our Retrofit Builder class to create network requests to REST API with retrofit. This is where you define the base URL of the API along with other configurations.

The getAPIInterfaceObject() method in the above code will be called every time while setting up a Retrofit interface.

Few important terms from the above code snippet

Read Timeout:

The read timeout starts to pay attention once the connection is established and then watches how fast (or slow) every byte gets transferred. If the time between two bytes gets larger than the read timeout, it'll count the request as failed. The counter resets after every incoming byte.

Write Timeout:

The write timeout is the opposite direction of the read timeout. It checks how fast you can send bytes to the server. Of course, it also gets reset after every successful byte. However, if sending a single byte takes longer than the configured write timeout limit, Retrofit will count the request as failed.

Connect Timeout

The connection timeout is likely the most important timeout. It is the time that lasts from starting the request to a completed TCP handshake with the server. In other words, if Retrofit couldn’t establish a connection to the server within the set connection timeout limit, it’ll count the request as failed.

Call Timeout

The call timeout sets the default timeout for complete calls. The call timeout spans the entire call: resolving DNS, connecting, writing the request body, server processing, and reading the response body. In other words, if the entire API call from start to finish does not complete in said time limit then it will count the request as failed.

Now we are done with the setup and let’s call our API from our activity class.

enqueue() asynchronously sends the request and notifies your app with a callback when a response comes back. Since this request is asynchronous, Retrofit handles it on a background thread so that the main UI thread isn't blocked or interfered with.

To use enqueue(), you have to implement two callback methods:

  • onResponse()
  • onFailure()

If everything goes well then callback will fall on OnResponse() method from where you can update your API and if there's any error or exception then onFailure() method will be called.

That’s it for now!!
Thanks for reading and don’t forget to share with your fellow developers :)
This post was originally posted on
CodeTheraphy.com.

For more articles follow me on Medium and CodeTheraphy.com you can also connect me on LinkedIn

--

--