Basic: Use a Server backend

This example shows how to both serve an application HttpHandler using an embedded HTTP server and to query it using an HTTP client. All server-backend implementations are launched in an identical manner (in 1LOC) using implementations of the ServerConfig interface - and a base implementation of this interface is provided for each server backend.

Alternatively, any http4k application can be mounted into any Servlet container using the asServlet() extension method. This is the mechanism used in the Jetty implementation.

Gradle setup

implementation group: "org.http4k", name: "http4k-core", version: ""
implementation group: "org.http4k", name: "http4k-client-apache", version: ""
implementation group: "org.http4k", name: "http4k-server-jetty", version: ""


package guide.howto.use_a_server_backend

import org.http4k.client.ApacheClient
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.server.Jetty
import org.http4k.server.asServer

fun main() {

    val app = { request: Request -> Response(OK).body("Hello, ${request.query("name")}!") }

    val jettyServer = app.asServer(Jetty(9000)).start()

    val request = Request(Method.GET, "http://localhost:9000").query("name", "John Doe")

    val client = ApacheClient()