### Basic WebDriver Setup Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/webdriver/index.html Demonstrates the minimal setup required to get a WebDriver instance for testing. This is useful for starting any automated browser interaction. ```kotlin import org.http4k.client.WebDriver import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.then import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = org.http4k.core.HttpHandler { Request(GET, "/") -> org.http4k.core.Response(org.http4k.core.Status.OK).body("Hello http4k!") } val server = app.asServer(Netty(0)).start() val driver = WebDriver(server) println(driver.get("/")) server.stop() } ``` -------------------------------- ### Example: Basic HTTP Server Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/contributing/index.html A simple http4k application demonstrating a basic HTTP server setup. This example shows how to define a route and start a server. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = DebuggingFilters.PrintRequest().then( routes( "/" bind GET to { Response(OK).body("Hello, http4k!") } ) ) fun main() { val server = app.asServer(Netty(9000)).start() println("Server started on port ${server.port()}") } ``` -------------------------------- ### Basic http4k App Setup Source: https://github.com/http4k/http4k.github.io/blob/master/news/tale-of-the-tape-claude-vs-http4k/index.html Demonstrates the minimal setup for an http4k application, including defining routes and starting the server. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = routes( "/" / Path.fixed("name") bind GET to { req -> Response(OK).body("Hello, ${req.path("name")}!") } ) fun main() { val appWithFilter = DebuggingFilters.PrintRequest().then(app) appWithFilter.asServer(Netty(9000)).start() } ``` -------------------------------- ### Server Implementation Examples Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/reference/overview/index.html Provides examples of starting an HTTP4K server using different underlying server implementations. ```kotlin // SunHttp (built-in) val sunHttpServer = app.asServer(SunHttp(9000)).start() // Jetty val jettyServer = app.asServer(Jetty(9000)).start() // Netty val nettyServer = app.asServer(Netty(9000)).start() // Apache val apacheServer = app.asServer(Apache(9000)).start() ``` -------------------------------- ### Basic http4k Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/news/http4k-v6-still-the-most-testable-web-toolkit-on-the-planet/index.html A minimal http4k server setup demonstrating the core components and how to start a basic HTTP server. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.lens.Path import org.http4k.lens.string import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app: HttpHandler = routes( "/hello" bind GET to { request: Request -> val name = Path.string().map(String::capitalize).required("name") Response(OK).body("Hello, ${name(request)}!") } ) val server = DebuggingFilters.PrintRequest().then(app).asServer(Netty(9000)).start() println("Server started on http://localhost:${server.port()}") } ``` -------------------------------- ### Basic Agent Setup Source: https://github.com/http4k/http4k.github.io/blob/master/_sites/agents/index.html Demonstrates the fundamental setup for an HTTP4K agent. This is useful for starting new projects or understanding the core agent structure. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.ServerFilters.CatchAll import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app: HttpHandler = routes( "/hello" bind GET to { request -> val name = Path.of("name") val nameValue = name(request) Response(OK).body("Hello, $nameValue!") } ) CatchAll(app).asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic WebSocket Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/howto/serve_websockets/index.html Demonstrates the minimal configuration required to start a WebSocket server with HTTP4K. This setup listens for incoming WebSocket connections. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer import org.http4k.websocket.WsHandler import org.http4k.websocket.WsMessage import org.http4k.websocket. நோக்க val app: HttpHandler = routes( "" bind { Response(OK) }, "ws" bind நோக்க { onConnected { println("Client connected") } onMessage { msg: WsMessage -> println("Received message: ${msg.body}") send(WsMessage("Echo: ${msg.body}")) } onDisconnected { println("Client disconnected") } } ) fun main() { app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic HTTP4K Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/_sites/connect/index.html Demonstrates the fundamental setup of an HTTP4K server with a simple route. This is the starting point for most HTTP4K applications. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = DebuggingFilters.PrintRequest().then( routes( "/" bind GET to { Response(OK).body("Hello, World!") }, "/users/{name}" bind GET to { req -> val name = Path("name").invoke(req) Response(OK).body("Hello, $name!") } ) ) fun main() { val server = app.asServer(Netty(9000)).asServer(Netty(9000)) println("Server started on http://localhost:9000") server.start() } ``` -------------------------------- ### Systems Manager Client Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/reference/amazon/systemsmanager/index.html Demonstrates how to create and use a Systems Manager client, showing both real and fake client options. It includes examples of putting and getting parameters. ```kotlin package content.ecosystem.connect.reference.amazon.systemsmanager import dev.forkhandles.result4k.Result import org.http4k.aws.AwsCredentials import org.http4k.client.JavaHttpClient import org.http4k.connect.RemoteFailure import org.http4k.connect.amazon.core.model.Region import org.http4k.connect.amazon.systemsmanager.FakeSystemsManager import org.http4k.connect.amazon.systemsmanager.Http import org.http4k.connect.amazon.systemsmanager.SystemsManager import org.http4k.connect.amazon.systemsmanager.action.PutParameterResult import org.http4k.connect.amazon.systemsmanager.getParameter import org.http4k.connect.amazon.systemsmanager.model.ParameterType import org.http4k.connect.amazon.systemsmanager.model.SSMParameterName import org.http4k.connect.amazon.systemsmanager.putParameter import org.http4k.core.HttpHandler import org.http4k.filter.debug const val USE_REAL_CLIENT = false fun main() { val paramName = SSMParameterName.of("name") // we can connect to the real service or the fake (drop in replacement) val http: HttpHandler = if (USE_REAL_CLIENT) JavaHttpClient() else FakeSystemsManager() // create a client val client = SystemsManager.Http(Region.of("us-east-1"), { AwsCredentials("accessKeyId", "secretKey") }, http.debug()) // all operations return a Result monad of the API type val putParameterResult: Result = client.putParameter(paramName, "value", ParameterType.String) println(putParameterResult) // get the parameter back again println(client.getParameter(paramName)) } ``` -------------------------------- ### Basic http4k Application Setup Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/your_first_http4k_app/index.html This snippet shows the minimal setup for an http4k application. It defines a simple 'Hello World' endpoint and starts an embedded Jetty server. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = DebuggingFilters.PrintRequest().then(routes( "/" bind GET to { Response(OK).body("Hello, http4k!") }, "/user/{name}" bind GET to { request -> val name = Path.of("name")(request) Response(OK).body("Hello, $name!") } )) fun main() { app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic Approval Test Setup Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/approvaltests/index.html Demonstrates the minimal setup required to start using Approval Tests with http4k. Ensure you have the necessary Maven/Gradle dependencies. ```kotlin import org.http4k.client.OkHttpExtensions.client import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.ClientFilters.SetBaseUriFromSystemProperty import org.http4k.server.ApacheServer import org.http4k.server.asServer import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.approvaltests.Approvals import org.approvaltests.reporters.Reporters @ExtendWith(org.http4k.testing.ApprovalTest::class) internal class ApprovalTest { @Test fun `hello world`() { val app = { _: Request -> Response(OK).body("hello world") } val server = app.asServer(ApacheServer()).start() val client = SetBaseUriFromSystemProperty(server).then(org.http4k.client.OkHttp()) // Use OkHttp client val response = client(Request(GET, "/")) Approvals.verify(response.bodyString(), Reporters.displayName) server.stop() } } ``` -------------------------------- ### TDing HTTP4K Setup and Basic Usage Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/tdding_http4k/part2/index.html Demonstrates the initial setup and basic usage of TDing HTTP4K, including necessary imports and a simple test case. ```kotlin import org.http4k.client.OkHttp3Client import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.ClientFilters.SetHost import org.http4k.lens.string import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = routes( "/" bind GET to { req: Request -> val name = "name"(req) Response(OK).body("Hello, $name!") } ) val server = app.asServer(Netty(9000)).start() val client = SetHost("localhost:9000").then(OkHttp3Client()) val request = Request(GET, "/").query("name", "http4k") val response: Response = client(request) println(response.status) println(response.bodyString()) server.stop() } ``` -------------------------------- ### Basic HTTP Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/reference/x402/index.html Demonstrates the fundamental setup of an HTTP server using the X402 library. This includes creating a server instance and binding it to a specific port. ```kotlin import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = { req: org.http4k.core.Request -> org.http4k.core.Response(org.http4k.core.Status.OK).body("Hello, http4k!") } app.asServer(org.http4k.server.Netty(9000)).start() } ``` -------------------------------- ### Basic http4k Server Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/index.html A simple http4k server that responds with 'Hello, http4k!' to any request. This is a fundamental example for getting started with http4k. ```kotlin import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = routes( "/" bind GET to { Response(OK).body("Hello, http4k!") } ) app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/howto/use_a_server_backend/index.html Demonstrates the fundamental setup for an http4k server using a simple handler. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = { request -> Response(OK).body("Hello, ${request.method} ${request.uri.path}!") } fun main() { val decoratedApp = DebuggingFilters.PrintRequest().then(app) decoratedApp.asServer(Netty(9000)).start() } ``` -------------------------------- ### GraphQL Server and Client Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/graphql/index.html Demonstrates setting up a GraphQL server with http4k, defining queries, and then consuming it from a client. Includes server startup and a sample client request. ```kotlin package content.ecosystem.http4k.reference.graphql import com.expediagroup.graphql.generator.SchemaGeneratorConfig import com.expediagroup.graphql.generator.TopLevelObject import com.expediagroup.graphql.generator.toSchema import graphql.GraphQL.newGraphQL import org.http4k.client.JavaHttpClient import org.http4k.client.asGraphQLHandler import org.http4k.core.HttpHandler import org.http4k.core.Uri import org.http4k.graphql.GraphQLHandler import org.http4k.graphql.GraphQLRequest import org.http4k.graphql.GraphQLResponse import org.http4k.routing.bind import org.http4k.routing.graphQL import org.http4k.routing.graphQLPlayground import org.http4k.routing.routes import org.http4k.server.SunHttp import org.http4k.server.asServer object MyGraphQLHandler : GraphQLHandler { private val graphQL = newGraphQL( toSchema( SchemaGeneratorConfig(supportedPackages = listOf("content.ecosystems.http4k.module.graphql")), listOf(TopLevelObject(UserQueries())), listOf() ) ).build() override fun invoke(request: GraphQLRequest) = GraphQLResponse.from(graphQL.execute(request.query)) } data class User(val id: Int, val name: String) data class Params(val ids: List) class UserQueries { private val userDb = listOf( User(id = 1, name = "Jim"), User(id = 2, name = "Bob"), ) fun search(params: Params) = userDb.firstOrNull { it.id in params.ids } } fun main() { val app: HttpHandler = routes( "/graphql" bind graphQL(MyGraphQLHandler), graphQLPlayground(Uri.of("/graphql")) ) // serve GQL queries/mutations at /graphql app.asServer(SunHttp(8000)).start() // for clients, just convert any app into a GQL handler val gql: GraphQLHandler = JavaHttpClient().asGraphQLHandler(Uri.of("http://localhost:8000/graphql")) val response: GraphQLResponse = gql( GraphQLRequest( """ { search(params: { ids: [1]}) { id name } } """ ) ) println(response) println("You can visit the GraphQL playground at: http://localhost:8000") } ``` -------------------------------- ### Initialize OpenFeature SDK Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/reference/openfeature/index.html Initialize the OpenFeature SDK with a provider. This is a basic setup for getting started. ```javascript import { OpenFeature } from '@openfeature/server-sdk'; const provider = new MyProvider(); // Replace with your actual provider OpenFeature.setProvider(provider); OpenFeature.setLogger(new MyLogger()); // Optional: set a custom logger ``` -------------------------------- ### Basic http4k Application Setup Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/tdding_http4k/part1/index.html This snippet shows the minimal setup for an http4k application, including necessary imports and the main function. It serves as the starting point for TDD development. ```kotlin package com.example.app import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.ApacheServer import org.http4k.server.asServer fun app(): HttpHandler = routes( "/" bind GET to { Response(OK).body("Hello, World!") } ) fun main() { val app = DebuggingFilters.PrintRequest().then(app()) println("Starting server on http://localhost:9000") app.asServer(ApacheServer(9000)).start() } ``` -------------------------------- ### Basic HTTP Request Example Source: https://github.com/http4k/http4k.github.io/blob/master/howto/integrate_with_openapi/index.html A simple example demonstrating how to make an HTTP GET request using a common library. Ensure the library is installed and imported. ```javascript const axios = require('axios'); async function fetchData(url) { try { const response = await axios.get(url); console.log('Data:', response.data); } catch (error) { console.error('Error fetching data:', error); } } fetchData('https://api.example.com/data'); ``` -------------------------------- ### Basic http4k App Setup Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/your_first_http4k_app/index.html This snippet shows the minimal setup for an http4k application. It defines a simple route that responds with 'Hello World!' to any request. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = DebuggingFilters.PrintRequest().then( routes( "/" bind GET to { request -> Response(OK).body("Hello World!") } ) ) fun main() { app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic HTTP Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/_sites/connect/index.html Demonstrates how to create a simple HTTP server using HTTP4K. This is the foundational step for any HTTP4K application. ```kotlin import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = { request: org.http4k.core.Request -> org.http4k.core.Response(org.http4k.core.Status.OK).body("Hello, HTTP4K!") } app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Initialize OpenFeature SDK Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/reference/openfeature/index.html Initializes the OpenFeature SDK with a default provider. This is a basic setup for getting started. ```kotlin import dev.openfeature.sdk.* fun main() { OpenFeature.setProvider(InMemoryProvider()) val client = OpenFeature.getClient() val booleanValue = client.getBooleanDetails("my-boolean-flag") println("Boolean flag: ${booleanValue.value}") val stringValue = client.getStringDetails("my-string-flag") println("String flag: ${stringValue.value}") val numberValue = client.getNumberDetails("my-number-flag") println("Number flag: ${numberValue.value}") val objectValue = client.getObjectDetails("my-object-flag") println("Object flag: ${objectValue.value}") } ``` -------------------------------- ### Server Example: Apache Server Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/tdding_http4k/index.html Demonstrates how to start an http4k application using the Apache Server implementation. This is one of the available server backends. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.ApacheServer import org.http4k.server.asServer val app: HttpHandler = routes( "/" bind GET to { Response(OK).body("Hello, World!") } ) fun main() { println("Starting server on http://localhost:9000") app.asServer(ApacheServer(9000)).start() } ``` -------------------------------- ### Basic HTTP Server Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/core/index.html A simple http4k server that responds with 'Hello, World!' to any request. This is a fundamental example to get started with http4k. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = DebuggingFilters.PrintRequest().then( routes( "/" bind GET to { Response(OK).body("Hello, World!") }, "/users/{id}" bind GET to { req -> val id = Path.of("id")(req) Response(OK).body("User ID: $id") } ) ) fun main() { app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic HTTP4K Application Source: https://github.com/http4k/http4k.github.io/blob/master/community/index.html A simple HTTP4K application that echoes the request method and URI. This serves as a fundamental example for getting started. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.lens.string import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer fun app(): HttpHandler = routes( "/" bind GET to { request -> Response(OK).body("Hello, ${request.method} ${request.uri.path}!") } ) fun main() { val app = app() println("Starting server on http://localhost:9000") app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic Templating Setup Source: https://github.com/http4k/http4k.github.io/blob/master/howto/use_a_templating_engine/index.html Demonstrates the minimal setup required to initialize and use a templating engine with HTTP4K. This is useful for simple rendering tasks. ```kotlin import org.http4k.template.HandlebarsTemplates val renderer = HandlebarsTemplates() val template = renderer( """

Hello {{name}}!

""" ) val viewModel = object { val name = "World" } println(template(viewModel)) ``` -------------------------------- ### Initialize and Run MCP Server Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/create_an_mcp_server/index.html This snippet shows the basic commands to initialize a new MCP server and start it. Ensure you have MCP installed. ```bash mcp init mcp start ``` -------------------------------- ### Basic HTTP Server Source: https://github.com/http4k/http4k.github.io/blob/master/_sites/outbox/index.html A simple HTTP server using Http4k to handle requests and return responses. This is a fundamental example for getting started. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Route import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = DebuggingFilters.PrintRequest().then( routes( "/" bind GET to { Response(OK).body("Hello, World!") }, "/users" bind GET to { Response(OK).body("Users list") } ) ) fun main() { app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic Integration Test Setup Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/tdding_http4k/part3/index.html Demonstrates the basic setup for an integration test using http4k. This involves creating an app and a client to interact with it. ```kotlin class MyTest { @Test fun `my app returns hello world`() { val app = MyLenses.app val client = app.toClient() val response = client(Request(Method.GET, "/")) assertThat(response.status.code).isEqualTo(200) assertThat(response.bodyString()).isEqualTo("Hello World!") } } ``` -------------------------------- ### Serve a Simple Websocket Source: https://github.com/http4k/http4k.github.io/blob/master/howto/serve_websockets/index.html This example demonstrates how to create and start a basic websocket server that sends a 'hello' message upon connection. ```kotlin package content.howto.serve_websockets import org.http4k.server.Jetty import org.http4k.server.asServer import org.http4k.websocket.Websocket import org.http4k.websocket.WsMessage val server = { ws: Websocket -> ws.send(WsMessage("hello")) }.asServer(Jetty(9000)).start() ``` -------------------------------- ### Hot Reload Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/_md/ecosystem/http4k/reference/hot_reload/index.md Configure and start the HotReloadServer by implementing the HotReloadable interface. This example uses the default port 8000 and SunHttp server. ```kotlin package ecosystem.http4k.reference.hot_reload import content.ecosystem.http4k.reference.hot_reload.MyApp import org.http4k.core.HttpHandler import org.http4k.hotreload.HotReloadServer import org.http4k.hotreload.HotReloadable // This class is needed to create a HotReloadable instance of the HttpHandler class ReloadableHttpApp : HotReloadable { override fun create() = MyApp() } fun main() { // Start the HotReloadServer - configuration is available for non-standard setups HotReloadServer.http().start() } ``` -------------------------------- ### Running http4k app within Playwright tests Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/playwright/index.html This example demonstrates how to start an http4k application directly within your Playwright test setup. This ensures the application is running before tests begin and is shut down afterwards. ```kotlin import com.microsoft.playwright.Playwright import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = { request -> "Hello, ${request.uri.path}!" } val server = app.asServer(Netty(9000)).start() val playwright = Playwright.create() val browser = playwright.chromium().launch() val page = browser.newPage() page.navigate("http://localhost:9000/world") println(page.content()) browser.close() playwright.close() server.stop() } ``` -------------------------------- ### Creating an HTTP Server Source: https://github.com/http4k/http4k.github.io/blob/master/_sites/backoffice/index.html Shows how to set up a basic HTTP server that responds to requests. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.lens.Path import org.http4k.lens.string import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = routes( "/hello" bind GET to { Response(OK).body("Hello, World!") }, "/user/{name}" bind GET to { request -> val name = Path.string().of("name")(request) Response(OK).body("Hello, $name!") } ) fun main() { val printingApp = DebuggingFilters.PrintRequest().then(app) val server = printingApp.asServer(Netty(9000)).start() println("Server started on http://localhost:9000") // To stop the server later: // server.stop() } ``` -------------------------------- ### Creating an HTTP Client Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/tdding_http4k/part1/index.html This example shows how to make a GET request to a specified URL using HTTP4K's client capabilities. Ensure http4k-client-apache is included. ```kotlin import org.http4k.client.Apache import org.http4k.core.Method.GET import org.http4k.core.Request val client = Apache() val request = Request(GET, "http://localhost:9000/") val response = client(request) println(response.status) println(response.bodyString()) ``` -------------------------------- ### DynamoDB Table Repository Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/reference/amazon/dynamodb/index.html Demonstrates the full lifecycle of interacting with a DynamoDB table using the http4k Table Mapper, including client setup (real or fake), table creation, saving, getting, scanning, and deleting items. ```kotlin package content.ecosystem.connect.amazon.dynamodb import org.http4k.aws.AwsCredentials import org.http4k.client.JavaHttpClient import org.http4k.connect.amazon.core.model.Region import org.http4k.connect.amazon.dynamodb.DynamoDb import org.http4k.connect.amazon.dynamodb.FakeDynamoDb import org.http4k.connect.amazon.dynamodb.Http import org.http4k.connect.amazon.dynamodb.mapper.tableMapper import org.http4k.connect.amazon.dynamodb.model.Attribute import org.http4k.connect.amazon.dynamodb.model.TableName import org.http4k.filter.debug import java.util.UUID private const val USE_REAL_CLIENT = false // define our data class private data class Person( val name: String, val id: UUID = UUID.randomUUID() ) private val john = Person("John") private val jane = Person("Jane") fun main() { // build client (real or fake) val http = if (USE_REAL_CLIENT) JavaHttpClient() else FakeDynamoDb() val dynamoDb = DynamoDb.Http(Region.CA_CENTRAL_1, { AwsCredentials("id", "secret") }, http.debug()) // defined table mapper val table = dynamoDb.tableMapper( tableName = TableName.of("people"), hashKeyAttribute = Attribute.uuid().required("id") ) // create table table.createTable() // save table.save(john) table.save(jane) // get val johnAgain = table.get(john.id) // scan val people = table.primaryIndex().scan().take(10) // delete table.delete(john) } ``` -------------------------------- ### HTTP Client Setup with Default Configuration Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/concepts/clients/index.html Demonstrates how to create a basic HTTP client using the default configuration. This is suitable for most common use cases. ```kotlin import org.http4k.client.OkHttp" val client = OkHttp() ``` -------------------------------- ### Basic http4k App Setup Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/your_first_http4k_app/index.html This snippet shows the minimal setup for an http4k application. It requires importing necessary http4k modules. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.DebuggingFilters import org.http4k.routing.bind import org.http4k.routing.routes val app: HttpHandler = DebuggingFilters.PrintRequest().then( routes( "/" bind GET to { Response(OK).body("Hello, http4k!") } ) ) fun main() { val server = org.http4k.server.Netty(::app) server.start() } ``` -------------------------------- ### Basic AI Client Setup Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k-ai/index.html Demonstrates how to initialize a basic http4k client for interacting with an AI service. Ensure necessary dependencies are included. ```kotlin import org.http4k.client.JavaHttpClient import org.http4k.core.HttpHandler val http: HttpHandler = JavaHttpClient() ``` -------------------------------- ### Get Installation Token Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/connect/reference/github/index.html Retrieves an installation access token for a specific GitHub App installation. ```kotlin val token = gitHubApp.installation("YOUR_INSTALLATION_ID").token() ``` -------------------------------- ### Creating an HTTP Client Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/tdding_http4k/part1/index.html This example demonstrates how to create an HTTP client using http4k to make requests to an external service. It shows a simple GET request. ```kotlin import org.http4k.client.JavaHttp import org.http4k.core.Method import org.http4k.core.Request val client = JavaHttp() val request = Request(Method.GET, "https://httpbin.org/get") val response = client(request) println(response.status) println(response.bodyString()) ``` -------------------------------- ### Making a GET Request with Node.js 'axios' Source: https://github.com/http4k/http4k.github.io/blob/master/news/documenting_apis_with_openapi/index.html This snippet shows how to perform a simple GET request using the 'axios' library in Node.js. Ensure 'axios' is installed (`npm install axios`). ```javascript const axios = require('axios'); async function getExample() { try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1'); console.log(response.data); } catch (error) { console.error('Error fetching data:', error); } } getExample(); ``` -------------------------------- ### Undertow Server Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/servers/index.html A basic example of starting an http4k application with the Undertow server. ```kotlin import org.http4k.server.Undertow import org.http4k.server.asServer fun main() { val app = { _: org.http4k.core.Request -> org.http4k.core.Response(org.http4k.core.Status.OK).body("Hello, http4k!") } app.asServer(Undertow(9000)).start() } ``` -------------------------------- ### Routing with http4k Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/tdding_http4k/part2/index.html Demonstrates how to define different routes for specific HTTP methods and paths. This example shows handling GET requests to "/" and POST requests to "/echo". ```kotlin import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Response import org.http4k.core.Status.OK import org.http4k.core.then import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = routes( "/" bind GET to { Response(OK).body("Hello, World!") }, "/echo" bind POST to { request -> Response(OK).body(request.bodyString()) } ) app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Jetty Server Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/servers/index.html A basic example of starting an http4k application with the Jetty server. ```kotlin import org.http4k.server.Jetty import org.http4k.server.asServer fun main() { val app = { _: org.http4k.core.Request -> org.http4k.core.Response(org.http4k.core.Status.OK).body("Hello, http4k!") } app.asServer(Jetty(9000)).start() } ``` -------------------------------- ### Creating a Simple HTTP Server Source: https://github.com/http4k/http4k.github.io/blob/master/_sites/mcp/index.html Sets up a basic HTTP server that responds to requests at the root path with a "Hello, World!" message. ```kotlin import org.http4k.core.HttpHandler\nimport org.http4k.core.Method.GET\nimport org.http4k.core.Response\nimport org.http4k.core.Status.Companion.OK\nimport org.http4k.core.then\nimport org.http4k.filter.DebuggingFilters.PrintRequest\nimport org.http4k.routing.bind\nimport org.http4k.routing.routes\nimport org.http4k.server.Netty\nimport org.http4k.server.asServer\n\nfun main() {\n val app: HttpHandler = routes(\n "/" bind GET to { Response(OK).body("Hello, World!") }\n )\n\n val printingApp = PrintRequest().then(app)\n\n val server = printingApp.asServer(Netty(9000)).start()\n println("Server started on http://localhost:9000")\n server.stop()\n} ``` -------------------------------- ### Handling Different HTTP Methods Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/serverless_http4k_with_aws_lambda/index.html Example showing how to define routes for different HTTP methods (GET, POST) using http4k's routing capabilities. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.ServerFilters.CatchAll import org.http4k.routing.bind import org.http4k.routing.routes val app: HttpHandler = CatchAll() .then(routes( "/" bind GET to { _: Request -> Response(OK).body("GET request received") }, "/" bind POST to { req: Request -> Response(OK).body("POST request received with body: ${req.bodyString()}") } )) // AWS Lambda handler function (simplified) fun lambdaHandler(event: Any, context: Any): Any { val request = Request(GET, "/") // Mock request val response = app(request) return mapOf( "statusCode" to response.status.code, "body" to response.bodyString() ) } ``` -------------------------------- ### Netty Server Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/servers/index.html A basic example of starting an http4k application with the Netty server. ```kotlin import org.http4k.server.Netty import org.http4k.server.asServer fun main() { val app = { _: org.http4k.core.Request -> org.http4k.core.Response(org.http4k.core.Status.OK).body("Hello, http4k!") } app.asServer(Netty(9000)).start() } ``` -------------------------------- ### Starting the http4k Server Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/your_first_http4k_app/index.html This snippet shows how to start the http4k server using the Netty adapter on port 9000 and prints the server port to the console. ```kotlin val server = printingApp.asServer(Netty(9000)).start() println("Server started on ${server.port()}") ``` -------------------------------- ### Netty Server Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/servers/index.html A basic example of starting an http4k application with the Netty server. ```kotlin import org.http4k.server.Netty import org.http4k.server.asServer fun main() { MyHttpHandler().asServer(Netty(9000)).start() } ``` -------------------------------- ### Basic Dependency Injection Setup Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/config/index.html Demonstrates the fundamental setup for dependency injection using http4k's configuration module. This is useful for managing application components and their lifecycles. ```kotlin import org.http4k.config.Environment import org.http4k.config.EnvironmentKey import org.http4k.lens.Lens // Define environment keys for configuration values val MY_APP_PORT = EnvironmentKey("MY_APP_PORT", intLens()) // Load environment from properties or system properties val env = Environment.defaultEnv // Access configuration values val port = MY_APP_PORT(env) println("Application will run on port: $port") ``` -------------------------------- ### Create a simple HTTP server Source: https://github.com/http4k/http4k.github.io/blob/master/company/index.html Shows how to set up a minimal HTTP server with a single route. ```kotlin val app: HttpHandler = { request -> Response(OK).body("Hello, World!") } val server = app.asServer(SunHttp(9000)).start() // To stop the server: server.stop() ``` -------------------------------- ### Scrollspy - Get Offset Height Example Source: https://github.com/http4k/http4k.github.io/blob/master/howto/use_a_custom_oauth_provider/index.html Internal method to get the visible height of the scroll element. ```javascript this._getOffsetHeight() ``` -------------------------------- ### Basic HTTP Request Example Source: https://github.com/http4k/http4k.github.io/blob/master/howto/secure_and_auth_http/index.html A simple example demonstrating how to make a basic HTTP GET request. ```javascript const http = require('http'); http.get('http://example.com/data', (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log(data); }); }).on('error', (err) => { console.error('Error: ' + err.message); }); ``` -------------------------------- ### Creating a Simple HTTP Server Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/concepts/http/index.html Provides an example of setting up a basic HTTP server that responds to requests. This is the foundation for building web services. ```kotlin import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.server.Netty import org.http4k.server.asServer val app: HttpHandler = { request: Request -> Response(OK).body("Hello, ${request.method} ${request.uri.path}!") } fun main() { val server = app.asServer(Netty(9000)).start() println("Server started on port ${server.port()}") } ``` -------------------------------- ### Basic MCP App Setup Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/build_a_simple_mcp_app/index.html Initializes the MCP client and connects to the server. Ensure the server address is correctly configured. ```javascript import { MCPClient } from '@mcp/client'; const client = new MCPClient('ws://localhost:8080'); client.on('open', () => { console.log('Connected to MCP server'); }); client.on('message', (message) => { console.log('Received message:', message); }); client.on('error', (error) => { console.error('MCP error:', error); }); client.on('close', () => { console.log('Disconnected from MCP server'); }); // Example of sending a message setTimeout(() => { client.send({ type: 'GREETING', payload: 'Hello from client!' }); }, 2000); ``` -------------------------------- ### Basic GET Request Source: https://github.com/http4k/http4k.github.io/blob/master/showcase/index.html Demonstrates a simple GET request to a specified URL. No special setup is required. ```kotlin import org.http4k.client.OkHttp" import org.http4k.core.Method.GET import org.http4k.core.Request val client = OkHttp.client val request = Request(GET, "https://httpbin.org/get") val response = client(request) println(response.status) println(response.bodyString()) ``` -------------------------------- ### Basic GraphQL Server Setup Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/graphql/index.html Demonstrates the minimal setup for a http4k GraphQL server. It requires a GraphQL schema and a HttpHandler. ```kotlin val schema = GraphQLSchema.newSchema() .query(GraphQLObjectType.newObject() .name("Query") .field { it.name("hello").type(Scalars.GraphQLString).dataFetcher { "world" } }) .build() val app: HttpHandler = routes( "/graphql" bind Method.POST to GraphQLHandler(schema) ) ``` -------------------------------- ### Main Entry Point for MCP Server Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/build_a_simple_mcp_app/index.html Sets up and starts the MCP server on a specified port using the Jetty server implementation. ```kotlin package content.tutorial.build_a_simple_mcp_app import org.http4k.server.Jetty import org.http4k.server.asServer fun main() { val server = RepoHealthChecker().asServer(Jetty(9000)).start() println("Server started on " + server.port()) } ``` -------------------------------- ### Serve and Query http4k Application with Jetty and Apache Client Source: https://github.com/http4k/http4k.github.io/blob/master/howto/use_a_server_backend/index.html This Kotlin example sets up a simple http4k application, serves it using the embedded Jetty server, and then queries it using the Apache HTTP client. The server is started on port 9000 and the client sends a GET request with a query parameter. ```kotlin package content.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() println(client(request)) jettyServer.stop() } ``` -------------------------------- ### Handling a Simple GET Request Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/your_first_http4k_app/index.html Demonstrates how to define a route for a GET request to the root path and return a simple "Hello, http4k!" response. ```kotlin "/" bind GET to { Response(OK).body("Hello, http4k!") } ``` -------------------------------- ### Undertow Server Example Source: https://github.com/http4k/http4k.github.io/blob/master/ecosystem/http4k/reference/servers/index.html A basic example of starting an http4k application with the Undertow server. Requires the http4k-server-undertow dependency. ```kotlin import org.http4k.server.Undertow import org.http4k.server.asServer fun main() { val app = { _: org.http4k.core.Request -> org.http4k.core.Response(org.http4k.core.Status.OK).body("Hello, http4k!") } app.asServer(Undertow(9000)).start() } ``` -------------------------------- ### Starting the Lambda Server Source: https://github.com/http4k/http4k.github.io/blob/master/tutorial/serverless_http4k_with_aws_lambda/index.html Starts the http4k application configured for Lambda. The asServer(LambdaHttp).start() method prepares the application for deployment and execution within the AWS Lambda environment. ```kotlin app.asServer(LambdaHttp).start() ```