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.
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”.
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.
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:
- baseUrl: The base url of the server which you’re trying to connect. It should always end with ‘/’. A valid baseUrl would be https://184.108.40.206/api/v1/
- client: A retrofit object created using OkHttpClient.Builder object
- 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
This is just an interface with all the calls that you’re supposed to make to you server.
- 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.
- 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)
- 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.
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
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. ^_^