Http Client

Retrofit JSON Http API

Sometimes we might need to send requests over HTTP, and receive JSON response from the server. In this case, we can use the injectable candy provided by the Reactant.

Reactant will call the Retrofit library which is one of the most popular Java HTTP client libraries, and create a service object based on the interface you provided.

note

JSON is the most common way to transfer data nowadays, so that currently we only support direct injection of JSON response API, discuss with us if you found other important use cases that JSON API cannot fulfill your requirements. Merge requests are welcome!

Define API

Now we use a funny API called PokeAPI as an example, which allows us to get the info of the pokemon with the API!

import dev.reactant.reactant.extra.net.BaseUrl
import dev.reactant.reactant.extra.net.RetrofitJsonAPI
import retrofit2.http.GET
import retrofit2.http.Path
import io.reactivex.rxjava3.core.Maybe
// Define the response model class
// Since it is a little bit too long, so we just defined some fields
data class Pokemon(
val id: Int, val name: String,
val height: Int, val weight: Int,
val abilities: List<PokemonAbility>
)
data class Ability(val name: String, val url: String)
data class PokemonAbility(val is_hidden: Boolean, val ability: Ability)
// Define the API
@BaseUrl("https://pokeapi.co/api/v2/")
interface PokemonAPI {
@GET("pokemon/{name}")
fun getPokemon(@Path("name") name: String): Maybe<Pokemon>
}

Inject the API

To use the API we declared, we can simply inject it with RetrofitJsonAPI<T>, and call the function we just created.

Following examples shows how to make the request in the synchronous way and asynchronously way using the schedulers.

@Component
class PokemonTesting(
private val pokemonAPI: RetrofitJsonAPI<PokemonAPI>,
private val schedulerService: SchedulerService
) : LifeCycleHook {
override fun onEnable() {
// sync
pokemonAPI.service.getPokemon("butterfree")
.subscribe { MyFirstPlugin.log.info(it) }
// async
pokemonAPI.service.getPokemon("butterfree")
.subscribeOn(Schedulers.io())
.observeOn(schedulerService.mainThreadScheduler)
.subscribe { MyFirstPlugin.log.info(it) }
}
}

Different base url for different instance

To have different base url for each injection, you can specify the base url in @Inject()

@Component
class PokemonTesting(
@Inject("https://other-base-url.com/")
private val pokemonAPI: RetrofitJsonAPI<PokemonAPI>,
private val schedulerService: SchedulerService
)

Debugging requests

You can also turn on your API debugging feature by setting debugging = true to your service instance, which will enable the request logging.

override fun onEnable() {
pokemonAPI.debugging = true
}