cft

How to set up and use Retrofit in Android

This article assumes that you have a basic understanding of android development. Though, any previous knowledge about retrofit is not required.


user

Shivam Bhasin

2 years ago | 3 min read

This article assumes that you have a basic understanding of android development. Though, any previous knowledge about retrofit is not required.

Hello and welcome! If you’re looking to integrate retrofit in your project or probably looking for a structured way of setting up retrofit, then you’re at a right place. We’ll be doing this using a simple example. But first things first! What is retrofit?

What is retrofit?

Retrofit is a type face http client for android and java. It makes hitting api’s for and with data easy using annotations and callbacks.

An annotation is a form of syntactic metadata that can be added to Java source code. We can annotate classes, interfaces, methods, variables, parameters etc.

The concept of callbacks is to inform a class, synchronous or asynchronous, if some work in another class is done. Some call it the Hollywood principle: “Don’t call us we call you”.

Directory Structure

Create a package ‘network’ in your app’s root directory.

Then create 3 files in the package network: Api.java, RetrofitClient.java and APIService.java. Don’t worry we’ll discuss them one by one.

RetrofitClient.java

A simple retrofit client class looks like this. It contains getClient and getClientWithHeader methods which creates and returns a retrofit object. Commonly used retrofit builder options:

  1. baseUrl: The base url of the server which you’re trying to connect. It should always end with ‘/’. A valid baseUrl would be https://1.2.3.4/api/v1/
  2. client: A retrofit object created using OkHttpClient.Builder object
  3. addConverterFactory: GsonConverterFactory to parse the incoming json data to model classes

The getClientWithHeader method shows how to add custom headers like Authorization to the client object

The HttpLoggingInterceptor is added to the OkHttpClient.Builder object in debug mode. This will log all you requests in the Debug mode. Make sure you add this interceptor only when the build is debug else you’d be leaking some sensitive user data

APIService.java

This is just an interface with all the calls that you’re supposed to make to you server.

  1. You need to annotate your calls with the method of the request this call is supposed to make. Some examples would be @POST, @GET, @PATCH.
  2. The type of the call should match the response of the request. Or if you don’t want to use the data returned you can simply put JsonObject there. (We’ll discuss these models soon)
  3. The function parameters can be a JsonObject anotated with @Body, a path variable annotated with @Path or a query paramter with @Query. For a multipart(@Multipart) request this can be form data with @Part. These can be decided at runtime or can be hard coded.

Api.java

Finally the Api class which will use our RetrofitClient and ApiService to create a ApiService which can be used in activities and fragments to make calls. I used function overloading to request a service with authorization or without it depending on the token I pass to it during runtime.

Creating a basic model class

A very simple response model looks like this. Value of annotation @SerializedName should match the json object name to be parsed. The data types should also be the same as expected in the response otherwise this will throw a Json Parsing exception.

Note that I’ve used kotlin, and not java for this code. I prefer using kotlin over java for data model classes because it provides toString(), hashCode() and equals() functionality by default by just declaring your class as data

How to use

How do you use these classes, finally, in your app? A simple use case can be as below. We simply create an authorized instance of interface ApiService by using static method getApiService() from our Api class providing a token.

Then we simply enqueue the required method call from our ApiService interface based on user action(get user profile in this case). The enqueue method takes a Callback object of type defined during declaring this Call in our ApiService interface. You can update your UI in the overridden onFailure and onResponse methods with the callback object.

response.isSuccessful will be true when the response contains a 200 status code else false

That’s it!

Now you’re able to make network requests in android using retrofit. If you find this article helpful do clap for it. Comment for any doubts or reviews. ^_^

Upvote


user
Created by

Shivam Bhasin

Simplifying things since childhood. Writes about JavaScript, application development, and self-help.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles