To start, open the app module’s build.gradle file and add the following dependency:
implementation "com.squareup.retrofit2:retrofit:2.9.0"
Sync the project to apply changes.
After that, navigate to the networking package and create a file called MovieDiaryApiService.kt. You’ll use this interface to describe your interactions with the API. To do that, add the following code:
interface MovieDiaryApiService {
@POST("user/register")
fun registerUser()
@POST("user/login")
fun loginUser()
@GET("user")
fun getProfile()
@GET("movies")
fun getMovies()
@POST("movies")
fun makeEntry()
}
Appending Service to the end of the interface name is a naming convention you want to follow. Every function in the interface represents one interaction with the API. To specify what you want to do with an API, you annotated the functions with the appropriate HTTP method annotation. These annotations expect you to pass in a path as an argument. Retrofit then appends the path to the base URL to create a full API endpoint.
Now that the interface is ready, navigate to the networking package and create a file called RetrofitConfig.kt. This file will contain all the code needed to create a Retrofit instance. To start, define the BASE_URL like this:
private const val BASE_URL = "https://http-api-93211a10efe2.herokuapp.com/"
BASE_URL is a part of the full URL that will stay the same for all API endpoints. Always end the base URL with a slash. This ensures that Retrofit appends paths correctly. The next thing you need is an instance of OkHttpClient. Add the following code to create it:
private fun buildClient(): OkHttpClient = OkHttpClient.Builder().build()
buildClient() is a simple function that returns a new instance of OkHttpClient by obtaining its Builder() and call build(). Retrofit uses the client under the hood to make API calls.
Now that you have defined BASE_URL and the client, you can build a Retrofit instance. Add the following code:
private fun buildRetrofit(): Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(buildClient())
.build()
Retrofit uses the Builder pattern to create an instance. First, you get a new builder by calling Retrofit.Builder(), and then you add the previously defined BASE_URL, followed by the client, and ultimately calling build().
There’s one last step before you’re ready to make API calls. You must tell Retrofit which interface you want it to use. To do that, enter the following code:
fun buildMovieDiaryService(): MovieDiaryApiService =
buildRetrofit().create(MovieDiaryApiService::class.java)
You’re calling buildRetrofit() to get a new instance. Then, you invoke create(), passing in the previously created interface. Retrofit now knows how to generate implementations for the methods you defined in the interface.
You’re now ready to make the first API request using Retrofit.