Escriu per cercar…

API

Aquesta pàgina encara no s'ha traduït — es mostra en l'idioma original:English

Introduction

yaml
module.yaml
dependencies:
  - $ktor.server.contentNegotiation
  - $ktor.serialization.kotlinx.json

Content Negotiation

When you created the project, you included the Content Negotiation plugin. This plugin looks at the types of content that the client can render and matches these against the content types that the current service can provide. Hence, the term Content Negotiation.

In HTTP the client signals which content types it can render through the Accept header. The value of this header is one or more content types. In the case above you can examine the value of this header by using the development tools built into your browser.

Consider the following example:

text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7

Note the inclusion of */* .This header signals that it accepts HTML, XML or Images - but it would also accept any other content type.

The Content Negotiation plugin needs to find a format to send data back to the browser. If you look inside the generated code in the project, you will find a file called Serialization.kt inside src/main/kotlin/com/example, which includes the following:

kotlin
src/Application.kt
install(ContentNegotiation) {
    json()
}

This code installs the ContentNegotiation plugin, and also configures the kotlinx.serialization plugin. With this, when clients send requests, the server can send back objects serialized as JSON.

In the case of the request from the browser, the ContentNegotiation plugin knows it can only return JSON, and the browser will try to display anything it is sent. So the request succeeds.

Routes

GET

You can implement the routes for GET requests.

Differently from HTML previous example, the code can be simplified because you no longer need to worry about converting objects to HTML:

kotlin
src/Routing.kt
route("/product") {

    get {
        call.respond(products)
    }
}

Estàs llegint una vista prèvia.

Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.

Inicia sessió