Retrofit - GitKaran/Sample-Boot GitHub Wiki

Retrofit

  • A type-safe HTTP client for Android and Java
  • Retrofit turns your HTTP API into a Java interface
  • Annotations on the interface methods and its parameters indicate how a request will be handled
  • Every method must have an HTTP annotation (GET, POST, PUT, DELETE, and HEAD)
  • You can also specify query parameters in the URL with @Query aanotation
  • request URL can be updated dynamically using @Path annotation
  • An object can be specified for use as an HTTP request body with the @Body annotation
  • You can set static headers for a method using the @Headers annotation
  • Call instances can be executed either synchronously or asynchronously
  • Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization
  • CONVERTERS By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body. Converters can be added to support other types like Gson, Jackson
  • CUSTOM CONVERTERS If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easily create your own converter. Create a class that extends the Converter.Factory class and pass in an instance when building your adapter.

https://square.github.io/retrofit/
https://medium.com/tompee/creating-your-own-http-api-wrapper-library-retrofit-2-bc86dfc11b1c

Example

Introduce retrofit dependencies

<!-- https://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit -->
<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>retrofit</artifactId>
	<version>${retrofit.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.squareup.retrofit2/converter-jackson -->
<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>converter-jackson</artifactId>
	<version>2.3.0</version>
</dependency>

Create Retrofit builder for the class

interface PetStoreClientApi {
    // factory methods
    companion object {
        fun create(baseUrl: String): PetStore {

            val mapper = ObjectMapper()
                    .registerKotlinModule()

            val retrofit = Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(JacksonConverterFactory.create(mapper))
                    .build()

            return retrofit.create(PetStore::class.java)
        }
    }

}

Create an interface with retrofit annotations to define methods and its parameters to indicate how a request will be handled

interface PetStore {
    @GET("/v2/pet/findByStatus/{status}")
    fun findPetByStatus(
            @Path("status") status: String
    ): Call<ResponseBody>

    @GET("/v2/pet/{petId}")
    fun findPetByPetId(
            @Path("petId") petId: String
    ): Call<PetDto>

    @POST("/v2/pet")
    fun postNewPetInStore(
            @Body petDto: PetDto
    ): Call<PetDto>

    @PUT("/v2/pet")
    fun updateExistingPetInStore(
            @Body petDto: PetDto
    ): Call<PetDto>

    @DELETE("/v2/pet/{id}")
    fun deletePetFromStore(
            @Path("id") id: String
    ): Call<Void>
}

Access like below -

fun `Verify Pet Store`() {
        val mapper = jacksonObjectMapper()
        val dto = ClassPathResource("/src/main/kotlin/com/example/springboot/dto/dto.json").path
        val request = mapper.readValue<PetDto>(File(dto))
        val api = PetStoreClientApi.create("https://petstore.swagger.io")
        val response = api.postNewPetInStore(request).execute()
}        
⚠️ **GitHub.com Fallback** ⚠️