Escribe para buscar…

Ktorfit

Ktorfit is an HTTP client using KSP and Ktor clients.

Esta página todavía no se ha traducido — se muestra en su idioma original:English

Introduction

Ktorfit uses Kotlin Symbol Processing to generate type-safe HTTP client implementations based on annotated interfaces. It leverages Client’s powerful and flexible HTTP capabilities, making it easy to perform network operations in Kotlin applications.

Project

Create a new Kotlin project with Amper.

Update the module.yaml file to add the Ktorfit dependencies:

yaml
module.yaml
dependencies:
  - de.jensklingenberg.ktorfit:ktorfit-lib-light:2.6.4
  - io.ktor:ktor-client-cio:3.3.1
  - io.ktor:ktor-client-content-negotiation:3.3.1
  - io.ktor:ktor-serialization-kotlinx-json:3.3.1
settings:
  kotlin:
    ksp:
      processors:
        - de.jensklingenberg.ktorfit:ktorfit-ksp:2.6.4

You need to add ktorfit-kspfor KSP.

de.jensklingenberg.ktorfit:ktorfit-lib-light only add the Ktor client core dependency and not the platform dependencies for the clients (this gives you more control over the used clients).

When you want to use Ktor plugins for things like serialization, you need to add the dependencies.

Quick start

Let’s say you want to make a GET Request to https://swapi.dev/api/people/1/

Create a new Kotlin interface (it has to be defined inside a package, for example api):

kotlin
src/api/api.kt
@KtorfitGenerator
interface StarWars {
    @GET("people/1/")
    suspend fun getPerson(): String
}

Add a function that will be used to make our request. The @GET annotation will tell Ktorfit that this a GET request. The value of @GET is the relative URL path that will be appended to the base url which we set later.

An interface used for Ktorfit needs to have an HTTP method annotation on every function. Because Ktor relies on Coroutines by default, your functions need to have the suspend modifier.

Note

The return type String will return the response text. When you want directly parse the response into a class you need to add a JSON,XML, etc. converter to Ktor

Next we use the Ktorfit builder to create a Ktorfit instance and set the base url.

After compiling the project, we can then use the generated extension function createStarWars to receive an implementation of the wanted type.

kotlin
src/api/api.kt
fun build(): StarWars {
    val ktorfit = Ktorfit.Builder().baseUrl("https://swapi.dev/api/").build()
    return ktorfit.createStarWars()
}

Estás leyendo una vista previa.

Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.

Iniciar sesión