To interact with a remote HTTP API in Android app, your app needs to
establish a network connection to remote server which exposes your REST service and
communicate with that server, and then
receive its response data and
parse the data to be usable in your code.
Retrofit was made to do all these steps easily. For the last one, we need a converter to deserialize HTTP body. Several converters are available. We will use Moshi library
The mains goal of Retrofit is to turn your HTTP API into a Java interface. For example
interface RoomsApiService {
@GET("rooms")
fun findAll(): Call<List<RoomDto>>
@GET("rooms/{id}")
fun findById(@Path("id") id: Long): Call<RoomDto>
@PUT("rooms/{id}")
fun updateRoom(@Path("id") id: Long, @Body room: RoomCommandDto): Call<RoomDto>
}
Annotations (GET, POST, PUT, DELETE,…) on the interface methods and its parameters indicate how a request will be handled.
A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }.
You can bind a parameter in path
@GET("rooms/{id}")
fun findById(@Path("id") id: Long): Call<RoomDto>
@GET("rooms")
fun findAll(@Query("sort") sort: String): Call<List<RoomDto>>
An object can be specified for POST or PUT HTTP requests @Body annotation. In this case, Retrofit will use converter defined in your conf to serialize body object in JSON
@PUT("rooms/{id}")
fun updateRoom(@Path("id") id: Long, @Body room: RoomCommandDto): Call<RoomDto>
data class RoomDto(
val id: Long,
val name: String,
val currentTemperature: Double?,
val targetTemperature: Double?,
val windows: List<WindowDto>
)
data class RoomCommandDto(
val name: String,
val currentTemperature: Double?,
val targetTemperature: Double?,
val floor: Int = 1,
val buildingId: Long = -10
)
These 2 objects are 2 projections of a Room: one for the read, one for the update. You will find more information on Retrofit website
It is the time to test by yourself.