================ LIBRARY RULES ================ - Ignore anything with the term `printSource`. ================ CODE SNIPPETS ================ TITLE: Example Server Implementation DESCRIPTION: A complete example demonstrating the creation of a ZIO HTTP server with two routes: /greet (GET) and /echo (POST). SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_5 LANGUAGE: APIDOC CODE: ``` ## Example Server ### Description This example demonstrates how to create a ZIO HTTP server with two distinct routes: one for greeting users and another for echoing request bodies. ### Method N/A (This is a server setup example) ### Endpoint N/A (This is a server setup example) ### Parameters N/A ### Request Body N/A ### Response N/A ### Code Example ```scala import zio._ import zio.http._ object ExampleServer extends ZIOAppDefault { // A route that matches GET requests to /greet val greetRoute: Route[Any, Nothing] = Method.GET / "greet" -> handler { (req: Request) => val name = req.queryOrElse[String]("name", "World") Response.text(s"Hello $name!") } // A route that matches POST requests to /echo val echoRoute: Route[Any, Throwable] = Method.POST / "echo" -> handler { (req: Request) => req.body.asString.map(Response.text(_)) } // Aggregate routes and handle errors val routes: Routes[Any, Response] = Routes(greetRoute, echoRoute) .handleError(e => Response.internalServerError(e.getMessage)) // Serve the routes using the default server layer on port 8080 def run = Server.serve(routes).provide(Server.default) } ``` ``` -------------------------------- TITLE: Hello World Example in Scala DESCRIPTION: A simple 'Hello World' example for ZIO HTTP. It demonstrates the basic setup for creating an HTTP server. This code relies on the 'utils' object for printing the source code. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/hello-world.md#_snippet_0 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/HelloWorld.scala") ``` -------------------------------- TITLE: Start ZIO HTTP Certificate Chain Server Example DESCRIPTION: Command to run the ZIO HTTP server application that demonstrates TLS with intermediate CA-signed certificates. This command requires sbt to be installed and the ZIO HTTP example project to be available. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/implementing-tls-with-intermediate-ca-signed-server-certificate.md#_snippet_9 LANGUAGE: bash CODE: ``` sbt "zioHttpExample/runMain example.ssl.tls.intermediatecasigned.ServerApp" ``` -------------------------------- TITLE: Client-side Request Example DESCRIPTION: An example demonstrating how to create a GET request and send it using ZIO HTTP's client. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/request.md#_snippet_31 LANGUAGE: APIDOC CODE: ``` ## Client-side Example ### Description This example showcases how to construct a client request using `Request.get` and send it to a server endpoint using `Client.batched`, then process the response body. ### Method - `Request.get(url: String)`: Creates a new HTTP GET request. - `Client.batched(request: Request)`: Sends the given request using the ZIO HTTP client. ### Endpoint `http://localhost:8080/users/2` (Example endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```scala import zio._ import zio.http._ object ClientExample extends ZIOAppDefault { def run = Client .batched(Request.get("http://localhost:8080/users/2")) .flatMap(_.body.asString) .debug("Response Body: ") .provide(Client.default) } ``` ### Response #### Success Response (200 OK) - `Response`: The HTTP response from the server. #### Response Example ```json { "id": 2, "name": "Jane Doe", "email": "jane.doe@example.com" } ``` ``` -------------------------------- TITLE: Simple ZIO HTTP Client Example DESCRIPTION: A basic example demonstrating the usage of the ZIO HTTP client. This snippet provides a starting point for making HTTP requests with ZIO HTTP. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_28 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/SimpleClient.scala") ``` -------------------------------- TITLE: Running a ZIO HTTP Server Application DESCRIPTION: This example demonstrates how to run a ZIO HTTP server. It defines simple routes that return an OK response and then uses Server.serve() to start the server. The Server.default provides necessary dependencies for the server to run. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/routes.md#_snippet_16 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ object HelloWorld extends ZIOAppDefault { val routes: Routes[Any, Response] = Handler.ok.toRoutes override def run = Server.serve(routes).provide(Server.default) } ``` -------------------------------- TITLE: Running the Authentication Server Demo DESCRIPTION: This command demonstrates how to start the ZIO HTTP authentication server and serve the web client demo. It uses sbt to run the main class. Ensure you have sbt installed and the project configured correctly. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/authentication-with-opaque-bearer-tokens.md#_snippet_16 LANGUAGE: bash CODE: ``` sbt "zioHttpExample/runMain example.auth.bearer.opaque.AuthenticationServer" ``` -------------------------------- TITLE: Run ZIO HTTP Server Example DESCRIPTION: Command to start the ZIO HTTP example server, which is typically configured to use self-signed TLS certificates. This server will be the target for the client application. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/implementing-tls-with-self-signed-server-certificate.md#_snippet_7 LANGUAGE: bash CODE: ``` sbt "zioHttpExample/runMain example.ssl.tls.selfsigned.ServerApp" ``` -------------------------------- TITLE: Hello World with Middlewares Example in Scala DESCRIPTION: This example demonstrates how to apply middleware to a ZIO HTTP application. It shows how to chain middleware for enhanced request processing, logging, or other functionalities. The 'utils' object is used to display the source code. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/hello-world.md#_snippet_3 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/HelloWorldWithMiddlewares.scala") ``` -------------------------------- TITLE: ZIO HTTP Server Example DESCRIPTION: Sets up a ZIO HTTP server with two routes: one for GET /greet and another for POST /echo. The server is configured to handle basic requests and errors, serving on port 8080. It demonstrates the use of Routes, RoutePattern, and Handler. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_0 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ object ExampleServer extends ZIOAppDefault { // A route that matches GET requests to /greet // It doesn't require any service from the ZIO environment // so the first type parameter is Any // All its errors are handled so the second type parameter is Nothing val greetRoute: Route[Any, Nothing] = // The whole Method.GET / "greet" is a RoutePattern Method.GET / "greet" -> // The handler is a function that takes a Request and returns a Response handler { (req: Request) => val name = req.queryOrElse[String]("name", "World") Response.text(s"Hello $name!") } // A route that matches POST requests to /echo // It doesn't require any service from the ZIO environment // It is an unhandled route so the second type parameter is something other than Nothing val echoRoute: Route[Any, Throwable] = Method.POST / "echo" -> handler { (req: Request) => req.body.asString.map(Response.text(_)) } // The Routes that don't require any service from the ZIO environment, // so the first type parameter is Any. // All the errors are handled by turning them into a Response. val routes: Routes[Any, Response] = // List of all the routes Routes(greetRoute, echoRoute) // Handle all unhandled errors .handleError(e => Response.internalServerError(e.getMessage)) // Serving the routes using the default server layer on port 8080 def run = Server.serve(routes).provide(Server.default) } ``` -------------------------------- TITLE: Start ZIO HTTP TLS Server DESCRIPTION: Command to start the ZIO HTTP example server using sbt, which is configured for root CA signed TLS communication. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/implementing-tls-with-root-ca-signed-server-certificate.md#_snippet_9 LANGUAGE: bash CODE: ``` sbt "zioHttpExample/runMain example.ssl.tls.rootcasigned.ServerApp" ``` -------------------------------- TITLE: Call Greeting Server with ZIO HTTP Client DESCRIPTION: This example demonstrates how to create a client to interact with the ZIO HTTP greeting server. It makes a GET request to the '/greet' path with a 'name' query parameter and prints the response body. This requires ZIO and ZIO HTTP client dependencies. SOURCE: https://github.com/zio/zio-http/blob/main/README.md#_snippet_2 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ object GreetingClient extends ZIOAppDefault { val app = for { client <- ZIO.serviceWith[Client](_.host("localhost").port(8080)) request = Request.get("greet").addQueryParam("name", "John") response <- client.batched(request) _ <- response.body.asString.debug("Response") } yield () def run = app.provide(Client.default) } ``` -------------------------------- TITLE: ZIO HTTP Authentication Server Example DESCRIPTION: Demonstrates how to set up an authentication server using ZIO HTTP. This example showcases the server-side logic for handling authentication requests and responses. It requires the zio-http library. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/authentication.md#_snippet_0 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/AuthenticationServer.scala") ``` -------------------------------- TITLE: Start Application in Watch Mode (sbt) DESCRIPTION: This command starts the ZIO HTTP application within sbt and enables watch mode using sbt-revolver. The application will automatically recompile and restart when source files change. Pressing Enter stops watching but not the application. SOURCE: https://github.com/zio/zio-http/blob/main/docs/installation.md#_snippet_2 LANGUAGE: shell CODE: ``` ~reStart ``` -------------------------------- TITLE: Advanced Hello World Example in Scala DESCRIPTION: An advanced 'Hello World' example for ZIO HTTP, likely showcasing more complex routing or request handling. This code utilizes the 'utils' object to display its source. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/hello-world.md#_snippet_1 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/HelloWorldAdvanced.scala") ``` -------------------------------- TITLE: Run HTTP Server with ZIO HTTP DESCRIPTION: Demonstrates how to start an HTTP server using ZIO HTTP. This example creates a simple app that responds with an empty body and a 200 status code, configured to run on port 8090. Requires ZIO HTTP and ZIO libraries. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_13 LANGUAGE: scala CODE: ``` import zio.http._ import zio._ object HelloWorld extends ZIOAppDefault { val routes = Handler.ok.toRoutes override def run = Server.serve(routes).provide(Server.defaultWithPort(8090)) } ``` -------------------------------- TITLE: Hello World with CORS Example in Scala DESCRIPTION: An example of setting up a ZIO HTTP server with Cross-Origin Resource Sharing (CORS) enabled. This demonstrates how to configure CORS policies for your HTTP application. The 'utils' object is used to print the source code. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/hello-world.md#_snippet_2 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/HelloWorldWithCORS.scala") ``` -------------------------------- TITLE: Creating a Basic ZIO HTTP Request DESCRIPTION: This example shows how to create a basic HTTP GET request using the ZIO HTTP library. It initializes a Request object with a GET method and a root URL, utilizing default values for other parameters like version, headers, body, and remote address. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/request.md#_snippet_1 LANGUAGE: scala CODE: ``` import zio.http._ Request(method = Method.GET, url = URL(Path.root)) ``` -------------------------------- TITLE: Attaching Examples to PathCodec DESCRIPTION: Demonstrates how to use the PathCodec#example operator to associate example values with a PathCodec, enhancing clarity and testability. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_6 LANGUAGE: scala CODE: ``` import zio.http.codec._ val userId = PathCodec.int("user-id") ?? (Doc.p("The user id")) example ("user-id", 123) ``` -------------------------------- TITLE: Attaching Examples to PathCodecs DESCRIPTION: Provide example values for path segments using the `example` operator on a `PathCodec`. These examples are useful for documentation and testing. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_12 LANGUAGE: APIDOC CODE: ``` ## Attaching Examples to PathCodecs Add example values to your `PathCodec` definitions using the `example` operator. This helps illustrate expected values for path parameters. ```scala import zio.http.codec._ // Define a codec for user ID and attach an example value val userIdCodec = PathCodec.int("user-id") ?? (Doc.p("The user id")) example ("user-id", 123) // Define a codec for post ID and attach an example value val postIdCodec = PathCodec.string("post-id") ?? (Doc.p("The post id")) example ("post-id", "abc") // Combine them into a full path codec val examplePathCodec = PathCodec.empty / "users" / userIdCodec / "posts" / postIdCodec // The example can be inspected or used for documentation generation // examplePathCodec.schema.map(_.example) // Would contain information about the examples provided ``` ``` -------------------------------- TITLE: Create HTTP Client with ZIO HTTP DESCRIPTION: Provides an example of creating an HTTP client using ZIO HTTP to send requests and receive responses. It shows how to obtain the client service, send a GET request to 'localhost:8090', and log the response status. Requires ZIO HTTP and ZIO libraries. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_14 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ object ClientExample extends ZIOAppDefault { val app = for { client <- ZIO.serviceWith[Client](_.host("localhost").port(8090)) response <- client.batched(Request.get("/")) _ <- ZIO.debug("Response Status: " + response.status) } yield () def run = app.provide(Client.default) } ``` -------------------------------- TITLE: Simple Client Example DESCRIPTION: A basic example demonstrating the usage of the ZIO HTTP client to make simple HTTP requests. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_34 LANGUAGE: APIDOC CODE: ``` ## Simple Client Example This example showcases a basic client request using ZIO HTTP. ### Endpoint [See `SimpleClient.scala` for endpoint details] ### Request Example [See `SimpleClient.scala` for request body example if applicable] ### Response Example [See `SimpleClient.scala` for response body example if applicable] ``` -------------------------------- TITLE: Create a basic RoutePattern for GET /users DESCRIPTION: This example demonstrates the creation of a simple RoutePattern for a GET request to the '/users' path. It uses the Method.GET and a literal string segment. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/route_pattern.md#_snippet_1 LANGUAGE: scala CODE: ``` // GET /users val pattern: RoutePattern[Unit] = Method.GET / "users" ``` -------------------------------- TITLE: Generate ZIO HTTP Project using g8 Template (Shell) DESCRIPTION: This command uses the sbt giter8 template system to create a new ZIO HTTP project. It requires sbt to be installed. Running this command will prompt you for project details. SOURCE: https://github.com/zio/zio-http/blob/main/docs/installation.md#_snippet_1 LANGUAGE: shell CODE: ``` sbt new zio/zio-http.g8 ``` -------------------------------- TITLE: Endpoint API Overview DESCRIPTION: An introduction to the Endpoint API with a basic example of defining a GET endpoint for books with a query parameter and a response body. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_3 LANGUAGE: APIDOC CODE: ``` ## Overview of the Endpoint API The `Endpoint` API in ZIO HTTP offers a declarative approach to describing API endpoints. It serves as a DSL for defining endpoints, their inputs, and outputs, facilitating the generation of OpenAPI documentation and clients. The API separates the definition of an endpoint from its implementation. ### Example: Defining a Books Endpoint This example demonstrates defining an endpoint for `/books` that accepts a `String` query parameter `q` and returns a `List[Book]`. ```scala import zio._ import zio.http._ import zio.http.codec._ import zio.http.endpoint.Endpoint import zio.schema.DeriveSchema case class Book(title: String, authors: List[String]) object Book { implicit val schema = DeriveSchema.gen[Book] } val endpoint = Endpoint(RoutePattern.GET / "books") .query(HttpCodec.query[String]("q") examples (("example1", "scala"), ("example2", "zio"))) .out[List[Book]] ``` ### Implementing the Endpoint Once defined, an endpoint can be implemented using the `#implement` method, which takes a handler function and returns a `Route`. ```scala // Assuming BookRepo.find is defined elsewhere // val booksRoute = endpoint.implement(query => BookRepo.find(query)) ``` ### Generating OpenAPI Documentation The `OpenAPIGen` constructor can be used to generate OpenAPI specifications from defined endpoints. ```scala // val openAPI = OpenAPGen.fromEndpoints(title = "Library API", version = "1.0", endpoint) // val swaggerRoutes = SwaggerUI.routes("docs" / "openapi", openAPI) ``` ``` -------------------------------- TITLE: ZIO HTTP Server Setup with Flash Backend (Scala) DESCRIPTION: Sets up and runs a ZIO HTTP server with the defined routes and flash message backend. It provides the necessary ZIO layers for the server, an in-memory flash backend, and a mutable reference for storing users. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/headers/session/flash.md#_snippet_9 LANGUAGE: scala CODE: ``` val app = Routes(saveUserRoute, getUsersRoute, homeRoute) def run = Server.serve(app).provide(Server.default, Flash.Backend.inMemory, ZLayer(Ref.make(List.empty[User]))) ``` -------------------------------- TITLE: Run ZIO HTTP Certificate Chain Client Example DESCRIPTION: Command to run the ZIO HTTP client application that connects to the TLS server demonstrating certificate chains. This command also requires sbt and the ZIO HTTP example project. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/implementing-tls-with-intermediate-ca-signed-server-certificate.md#_snippet_10 LANGUAGE: bash CODE: ``` sbt "zioHttpExample/runMain example.ssl.tls.intermediatecasigned.ClientApp" ``` -------------------------------- TITLE: ZIO HTTP Authentication Client Example DESCRIPTION: Illustrates how to create an authentication client that interacts with an authentication server using ZIO HTTP. This example focuses on the client-side implementation for sending authentication credentials and handling server responses. It depends on the zio-http library. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/authentication.md#_snippet_1 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/AuthenticationClient.scala") ``` -------------------------------- TITLE: ZIO HTTP ClientServer Example DESCRIPTION: This example illustrates the interaction between a ZIO HTTP client and server. It's useful for understanding how to set up and test client-server communication within the ZIO ecosystem. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_29 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/ClientServer.scala") ``` -------------------------------- TITLE: ClientServer Example DESCRIPTION: An example illustrating the interaction between a ZIO HTTP client and a ZIO HTTP server. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_35 LANGUAGE: APIDOC CODE: ``` ## ClientServer Example This example demonstrates a client making requests to a server within the same application or test environment. ### Endpoint [See `ClientServer.scala` for endpoint details] ### Request Example [See `ClientServer.scala` for request body example if applicable] ### Response Example [See `ClientServer.scala` for response body example if applicable] ``` -------------------------------- TITLE: ZIO HTTP Basic Authentication Middleware Example DESCRIPTION: Shows how to implement basic authentication using middleware in ZIO HTTP. This example provides a reusable middleware component for securing HTTP endpoints with basic authentication. It requires the zio-http library and utility functions. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/authentication.md#_snippet_2 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/BasicAuth.scala") ``` -------------------------------- TITLE: Generate Certificates Script DESCRIPTION: Shell script to generate CA-signed certificates for TLS communication. This is a one-time setup step required before running the server and client examples. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/implementing-tls-with-root-ca-signed-server-certificate.md#_snippet_8 LANGUAGE: bash CODE: ``` cd src/main/resources/certs/tls/root-ca-signed ./generate-certificates.sh ``` -------------------------------- TITLE: Client-side Request Sending with ZIO HTTP DESCRIPTION: Provides a client-side example using `zio.http.Client` to send a GET request to a specified URL. It demonstrates how to use `Client.batched` to send the request and process the response body as a string. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/request.md#_snippet_26 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ object ClientExample extends ZIOAppDefault { def run = Client .batched(Request.get("http://localhost:8080/users/2")) .flatMap(_.body.asString) .debug("Response Body: ") .provide(Client.default) } ``` -------------------------------- TITLE: ZIO HTTP Authentication Client Example DESCRIPTION: Demonstrates how to implement authentication with the ZIO HTTP client. This example shows the process of obtaining a JWT token via a login request and then using it to access a protected route. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_30 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/AuthenticationClient.scala") ``` -------------------------------- TITLE: Server Usage with Custom Configurations DESCRIPTION: Explains how to start the ZIO HTTP Server with custom configurations by providing a `Server.Config` object. It lists available configuration options and shows how to modify them. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/server.md#_snippet_7 LANGUAGE: APIDOC CODE: ``` ## Starting a Server with Custom Configurations ### Description This section describes how to configure the ZIO HTTP Server with custom settings using the `Server.Config` class. It shows how to provide a custom configuration and lists the available options. ### Method `Server.serve` with custom `Server.Config` ### Endpoint N/A (Server startup) ### Parameters #### Request Body N/A ### Request Example ```scala import zio.http._ import zio._ val routes: Routes[Any, Response] = Routes( Method.GET / "hello" -> handler(Response.text("Hello, World!")) ) // Providing a custom Server.Config Server .serve(routes) .provide( ZLayer.succeed(Server.Config.default.port(8081)), Server.live ) // Customizing specific configuration options val config = Server.Config.default .idleTimeout(60.seconds) .gracefulShutdownTimeout(20.seconds) .requestDecompression(true) Server.serve(routes).provide(ZLayer.succeed(config), Server.live) ``` ### Response #### Success Response (Server Start) - The server starts listening with the specified custom configurations. #### Response Example N/A (Server startup is an effect) ### Server.Config Options ```scala final case class Config( sslConfig: Option[SSLConfig], address: InetSocketAddress, acceptContinue: Boolean, keepAlive: Boolean, requestDecompression: Decompression, responseCompression: Option[ResponseCompressionConfig], requestStreaming: RequestStreaming, maxInitialLineLength: Int, maxHeaderSize: Int, logWarningOnFatalError: Boolean, gracefulShutdownTimeout: Duration, webSocketConfig: WebSocketConfig, idleTimeout: Option[Duration], ) ``` ``` -------------------------------- TITLE: GET /books?id= (Imperative Style) DESCRIPTION: An example of an HTTP API endpoint for a bookstore written in an imperative style. It handles request parsing, validation, and response construction manually. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/http-codec.md#_snippet_38 LANGUAGE: APIDOC CODE: ``` ## GET /books?id= ### Description Retrieves a book from the bookstore based on its ID provided as a query parameter. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **id** (string) - Required - The unique identifier of the book to retrieve. ### Request Example ```json { "example": "GET /books?id=123" } ``` ### Response #### Success Response (200) - **Book** (object) - The book object if found. - **id** (string) - The book's ID. - **title** (string) - The book's title. - **author** (string) - The book's author. #### Error Response (404) - **message** (string) - An error message indicating the book was not found. #### Response Example (Success) ```json { "example": { "id": "123", "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams" } } ``` #### Response Example (Not Found) ```json { "example": { "message": "Book with id 123 not found." } } ``` ``` -------------------------------- TITLE: Combine Server Layers using Server.configured DESCRIPTION: Shows how to combine `Server.live` and `ZLayer.fromZIO(ZIO.config(Server.Config.config))` into a single layer using `Server.configured` for simplified server setup. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/integrate-with-zio-config.md#_snippet_13 LANGUAGE: scala CODE: ``` import utils._ printSource("zio-http-example/src/main/scala/example/config/HoconWithConfiguredLayerExample.scala") ``` -------------------------------- TITLE: Loading ZIO HTTP Server Configuration from Environment Variables DESCRIPTION: Demonstrates how to load ZIO HTTP `Server.Config` from environment variables using `ZIO.config` and `Server.Config.config`. It includes an example of mapping configuration keys to match environment variable naming conventions. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/integrate-with-zio-config.md#_snippet_6 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ object MainApp extends ZIOAppDefault { def run = { Server .install( Routes( Method.GET / "hello" -> handler(Response.text("Hello, world!")), ), ) .flatMap(port => ZIO.debug(s"Sever started on http://localhost:$port") *> ZIO.never) .provide( Server.live, ZLayer.fromZIO( ZIO.config(Server.Config.config.mapKey(_.replace('-', '_'))), ), ) } } ``` -------------------------------- TITLE: Access ZIO Services in Handlers (Counter Example) DESCRIPTION: Illustrates accessing ZIO services, specifically a `Ref[Int]`, within HTTP request handlers. This example creates a counter that increments based on a path parameter. Requires ZIO environment and Ref service. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_11 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ object CounterExample extends ZIOAppDefault { val routes: Routes[Ref[Int], Response] = Routes( Method.GET / "count" / int("n") -> handler { (n: Int, _: Request) => for { ref <- ZIO.service[Ref[Int]] res <- ref.updateAndGet(_ + n) } yield Response.text(s"Counter: $res") }, ) def run = Server.serve(routes).provide(Server.default, ZLayer.fromZIO(Ref.make(0))) } ``` -------------------------------- TITLE: GET /greet Endpoint DESCRIPTION: Handles GET requests to the /greet endpoint, allowing a 'name' query parameter to customize the greeting. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_6 LANGUAGE: APIDOC CODE: ``` ## GET /greet ### Description This endpoint handles GET requests to the `/greet` path. It optionally accepts a `name` query parameter to personalize the greeting. If no `name` is provided, it defaults to "World". ### Method GET ### Endpoint `/greet` ### Parameters #### Query Parameters - **name** (string) - Optional - The name to greet. ### Request Example `GET /greet?name=ZIOHTTP` ### Response #### Success Response (200) - **body** (string) - A greeting message. #### Response Example ```json "Hello ZIOHTTP!" ``` ``` -------------------------------- TITLE: Complete Cookie Authentication Client Example (Scala) DESCRIPTION: A comprehensive Scala example demonstrating the full lifecycle of cookie-based authentication using ZIO HTTP, including login, cookie extraction, and accessing protected routes. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/cookie-based-authentication.md#_snippet_17 LANGUAGE: scala CODE: ``` utils.printSource("zio-http-example/src/main/scala/example/auth/session/cookie/CookieAuthenticationClient.scala") ``` -------------------------------- TITLE: Handle HTTP Requests with ZIO HTTP DESCRIPTION: Demonstrates how to define routes and handlers to process GET and POST requests. It shows accessing request URL and headers for GET requests and request body for POST requests. Assumes ZIO HTTP library is available. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_10 LANGUAGE: scala CODE: ``` import zio.http._ import zio._ val routes = Routes( Method.GET / "fruits" / "a" -> handler { (req: Request) => Response.text("URL:" + req.url.path.toString + " Headers: " + req.headers) }, Method.POST / "fruits" / "a" -> handler { (req: Request) => req.body.asString.map(Response.text(_)) } ) ``` -------------------------------- TITLE: GET /resources - Output Headers Applied to All Outputs DESCRIPTION: This example demonstrates applying an output header ('Date') to all defined output types of an endpoint. The header will be present regardless of whether the response is an Article or a Book. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_31 LANGUAGE: APIDOC CODE: ``` ## GET /resources (Output Headers for All Outputs) ### Description This endpoint returns either an Article or a Book, and a 'Date' header is included with both response types. ### Method GET ### Endpoint /resources ### Parameters None ### Request Body None ### Response #### Success Response (200) - **Either[Article, Book]** - Represents a response that can be either an Article or a Book. - **Article**: - **title** (string) - The title of the article. - **author** (string) - The author of the article. - **Book**: - **title** (string) - The title of the book. - **author** (string) - The author of the book. - **Date** (Header) - The date header applied to all responses. #### Response Example (Article) ```json { "title": "Understanding ZIO HTTP", "author": "Jane Doe" } ``` #### Headers - **Date**: [RFC 7231 formatted date string] #### Response Example (Book) ```json { "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams" } ``` #### Headers - **Date**: [RFC 7231 formatted date string] ``` -------------------------------- TITLE: HTTP Client Usage DESCRIPTION: Explains how to create an HTTP client instance, send a GET request to a server, and process the response status. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_19 LANGUAGE: APIDOC CODE: ``` ## Client GET Request ### Description Uses the ZIO HTTP client to send a GET request to the root path ('/') of a server running on localhost:8090 and prints the response status. ### Method GET ### Endpoint http://localhost:8090/ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (e.g., 200) - **Status** - The HTTP status of the response. #### Response Example ``` Response Status: Status.Ok ``` ``` -------------------------------- TITLE: Server Startup and Configuration DESCRIPTION: Demonstrates how to configure and launch an HTTP server using Server.serve and provide it with default configurations, including a specific port. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_18 LANGUAGE: APIDOC CODE: ``` ## Server Serve ### Description Starts an HTTP server on a specified port that responds with a 200 OK status and empty content for all requests. ### Method N/A (Server Start) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **empty** - Responds with an empty body and 200 OK status. #### Response Example None (Server logs or client response for requests) ``` -------------------------------- TITLE: Server-side Usage Example DESCRIPTION: Example demonstrating how to use Body on the server-side to create a Response with custom content. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/body.md#_snippet_7 LANGUAGE: APIDOC CODE: ``` ## POST /hello ### Description This endpoint reads a string from the request body and returns a personalized greeting. ### Method POST ### Endpoint /hello ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (String) - Required - The name to include in the greeting. ### Request Example ```json { "name": "World" } ``` ### Response #### Success Response (200) - **message** (String) - A greeting message. #### Response Example ```json { "message": "Hello World!" } ``` ``` -------------------------------- TITLE: ZIO HTTP WebSocket Echo Example DESCRIPTION: A simple WebSocket echo server implemented with ZIO HTTP. This example demonstrates basic WebSocket functionality by receiving messages from a client and sending them back without modification. SOURCE: https://github.com/zio/zio-http/blob/main/docs/examples/websocket.md#_snippet_2 LANGUAGE: scala CODE: ``` import zio.http._ import zio.stream.ZStream object WebSocketEcho { val webSocketApp: WebSocketApp[Any] = WebSocketApp.foreach[Any, WebSocketError, WebSocketFrame](channel => channel.receiveAll[WebSocketError, Unit] { case Read.Text(text) => channel.send(write(text)) case _ => ??? }, ) val app: HttpApp[Any, Response] = Handler .webSocket("/ws") { (req: Request) => webSocketApp } .toResponse val run: ZIO[Server, Throwable, Nothing] = Server.serve(app).provide(Server.default) } ``` -------------------------------- TITLE: Full ZIO HTTP Flash Message Example in Scala DESCRIPTION: A complete ZIO HTTP application showcasing the setting and retrieving of multiple flash messages. It defines routes to set flash messages on one endpoint and retrieve/render them on another. This example demonstrates the integration of flash messages within a server context, including in-memory backend configuration. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/headers/session/flash.md#_snippet_21 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ import zio.http.template._ object ui { def renderNoFlash = Html.fromString("no-flash") def renderNotice(html: Html): Html = div(styleAttr := "background: green", html) def renderAlert(html: Html): Html = div(styleAttr := "background: red", html) def renderBothMessage(notice: Html, alert: Html): Html = notice ++ alert } object SetGetBothFlashExample extends ZIOAppDefault { val routes = Routes( Method.GET / "set-flash" -> handler { val setBoth: Flash.Setter[(String, String)] = Flash.setNotice("The form was submitted successfully!") ++ Flash.setAlert("You are reaching your quota!") Response .seeOther(URL.root / "get-flash") .addFlash(setBoth) }, Method.GET / "get-flash" -> handler { (req: Request) => val getBoth: Flash[Html] = Flash.getMessageHtml.foldHtml(ui.renderNotice, ui.renderAlert)(ui.renderBothMessage) Response.html( req.flash(getBoth).getOrElse(ui.renderNoFlash), ) }, ).sandbox def run = Server.serve(routes).provide(Server.default, Flash.Backend.inMemory) ``` -------------------------------- TITLE: Handling Incoming Requests DESCRIPTION: Demonstrates how to define routes and handle incoming requests using ZIO HTTP handlers. This example shows how to extract the request body as a string and return it in the response. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/request.md#_snippet_4 LANGUAGE: APIDOC CODE: ``` ## POST /echo ### Description Handles POST requests to the /echo endpoint, reads the request body as a UTF-8 string, and returns the body as the response. ### Method POST ### Endpoint /echo ### Parameters #### Request Body - **body** (string) - The content of the request. ### Request Example ```json { "message": "Hello, ZIO HTTP!" } ``` ### Response #### Success Response (200) - **body** (string) - The echoed request body. #### Response Example ```json { "message": "Hello, ZIO HTTP!" } ``` ``` -------------------------------- TITLE: Patching a ZIO HTTP Request with Headers and Query Params DESCRIPTION: This example demonstrates how to modify an existing ZIO HTTP request using the `patch` method. It starts with a GET request to a specific URL and then applies a patch that adds a Content-Type header and appends new query parameters, creating a new request object with the modifications. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/request.md#_snippet_3 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ Request .get("http://localhost:8080/users") .patch( Request.Patch( addHeaders = Headers(Header.ContentType(MediaType.application.`json`)), addQueryParams = QueryParams("role" -> Chunk("reviewer", "editor")) ) ) ``` -------------------------------- TITLE: Creating a Response from a WebSocketApp DESCRIPTION: Demonstrates how to create an HTTP response that upgrades to a WebSocket connection using `Response.fromWebSocketApp`. Includes an example of an echo server. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/response/response.md#_snippet_32 LANGUAGE: APIDOC CODE: ``` ## POST /echo ### Description Creates an HTTP response with a WebSocket connection that echoes back received messages. ### Method GET ### Endpoint /echo ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None (This is a server-side handler) ### Response #### Success Response (101 Switching Protocols) - **WebSocket Connection**: Establishes a WebSocket connection. #### Response Example (WebSocket connection established, no standard HTTP response body) ```scala import zio._ import zio.http._ object WebsocketExample extends ZIOAppDefault { val routes: Routes[Any, Response] = { Routes( Method.GET / "echo" -> handler { Response.fromSocketApp( WebSocketApp( handler { (channel: WebSocketChannel) => channel.receiveAll { case ChannelEvent.Read(message) => channel.send(ChannelEvent.read(message)) case other => ZIO.debug(other) } }, ), ) }, ) } def run = Server.serve(routes).provide(Server.default) } ``` ``` -------------------------------- TITLE: Client-side Usage Example DESCRIPTION: Example demonstrating how to use Body on the client-side to make a POST request with string content. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/body.md#_snippet_8 LANGUAGE: APIDOC CODE: ``` ## POST /hello (Client Request) ### Description This example shows how to send a POST request to the `/hello` endpoint with a string body and process the response. ### Method POST ### Endpoint http://localhost:8080/hello ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (String) - Required - The name to send in the request body. ### Request Example (The request body is dynamically generated from user input) ### Response #### Success Response (200) - **message** (String) - The greeting message from the server. #### Response Example ```json { "message": "Hello John!" } ``` ``` -------------------------------- TITLE: Full Server-Sent Events Example in ZIO HTTP DESCRIPTION: A complete ZIO HTTP application example that serves a stream of server-sent events. It demonstrates how to create an infinite stream of current timestamps and serve them via an HTTP endpoint, allowing clients to receive real-time updates. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/response/response.md#_snippet_21 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ import zio.stream._ import java.time.LocalDateTime import java.time.format.DateTimeFormatter.ISO_LOCAL_TIME object ServerSentExample extends ZIOAppDefault { val stream: ZStream[Any, Nothing, ServerSentEvent[String]] = ZStream.repeatWithSchedule( ServerSentEvent(ISO_LOCAL_TIME.format(LocalDateTime.now)), Schedule.spaced(1.second), ) val app = Routes( Method.GET / "events" -> handler { Response.fromServerSentEvents(stream) }, ) def run = Server.serve(app).provide(Server.default) } ``` -------------------------------- TITLE: ZIO HTTP Client mTLS Configuration and Request Example DESCRIPTION: This Scala code demonstrates how to configure a ZIO HTTP client for mTLS by specifying keystore and truststore resources and their passwords. It then makes a secure GET request to a localhost server and prints the response body. This requires the 'zio-http' and 'zio-config' libraries. SOURCE: https://github.com/zio/zio-http/blob/main/docs/guides/implementing-mutual-tls.md#_snippet_13 LANGUAGE: scala CODE: ``` import zio.Config.Secret import zio._ import zio.http._ import zio.http.netty.NettyConfig object ClientApp extends ZIOAppDefault { val app: ZIO[Client, Throwable, Unit] = for { _ <- Console.printLine("Making secure HTTPS requests...") textResponse <- Client.batched( Request.get("https://localhost:8443/hello"), ) textBody <- textResponse.body.asString _ <- Console.printLine(s"Text response: $textBody") } yield () private val config = ZClient.Config.default.ssl( ClientSSLConfig.FromJavaxNetSsl( keyManagerSource = ClientSSLConfig.FromJavaxNetSsl.Resource("certs/mtls/client-keystore.p12"), keyManagerPassword = Some(Secret("clientkeypass")), trustManagerSource = ClientSSLConfig.FromJavaxNetSsl.Resource("certs/mtls/client-truststore.p12"), trustManagerPassword = Some(Secret("clienttrustpass")), ), ) override val run = app.provide( ZLayer.succeed(config), ZLayer.succeed(NettyConfig.default), DnsResolver.default, ZClient.live, ) } ``` -------------------------------- TITLE: Parameterized Route Example DESCRIPTION: Demonstrates creating a route that extracts an integer ID from the URL path. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/overview.md#_snippet_8 LANGUAGE: APIDOC CODE: ``` ## GET /user/{id} ### Description This endpoint handles GET requests to `/user/{id}`, where `{id}` is a path parameter representing a user ID. The extracted integer ID is used in the response. ### Method GET ### Endpoint `/user/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the user. ### Request Example `GET /user/123` ### Response #### Success Response (200) - **body** (string) - A message indicating the requested user ID. #### Response Example ```json "Requested User ID: 123" ``` ``` -------------------------------- TITLE: UI Module Initialization and User Card Rendering DESCRIPTION: This JavaScript code defines the UI module for the Zio-HTTP project. The `init` function orchestrates the initial setup of the user interface, including rendering user cards, setting the initial user, updating the authentication state display, initializing the console, and clearing transaction details. The `_renderUserCards` method dynamically generates HTML for user cards based on the `Config.USERS` array. Dependencies include DOM, Config, CredentialManager, AuthState, and Logger. SOURCE: https://github.com/zio/zio-http/blob/main/zio-http-example/src/main/resources/digest-auth-client.html#_snippet_13 LANGUAGE: javascript CODE: ``` const UI = { init() { this._renderUserCards(); this._setInitialUser(); this.updateAuthStateDisplay(); this._initializeConsole(); this._clearTransactionDetails(); }, _renderUserCards() { const userGrid = DOM.get('userGrid'); if (!userGrid) return; userGrid.innerHTML = Config.USERS.map((user, index) => `

${user.name}

${user.role}

${user.email}

` ).join(''); }, _setInitialUser() { const firstUser = Config.USERS[0]; if (firstUser) { CredentialManager.set(firstUser.username, firstUser.password); } }, updateAuthStateDisplay() { const container = DOM.get('authStateContent'); if (!container) return; const state = AuthState.get(); if (!state.isValid || !state.nonce) { container.innerHTML = `

No active authentication session

`; return; } const ncFormatted = state.nc.toString().padStart(8, '0'); container.innerHTML = `
Username
${state.username || 'N/A'}
Realm
${state.realm || 'N/A'}
Nonce
${state.nonce ? state.nonce.substring(0, 20) + '...' : 'N/A'}
Algorithm
${state.algorithm || 'MD5'}
QOP
${state.qop || 'auth'}
NC (Request Count)
${ncFormatted}
`; }, _initializeConsole() { Logger.clear(); Logger.info('Server running on http://localhost:8080'); Logger.info('Users: john/password123, jane/secret456, admin/admin123'); }, _clearTransactionDetails() { const detailsContainer = DOM.get('transactionDetails'); if (detailsContainer) { detailsContainer.innerHTML = `

Click any endpoint button to see detailed HTTP request/response messages

`; DOM.hide(detailsContainer); } }, setActiveUser(username, password) { document.querySelectorAll('.user-card').forEach(card => { card.classList.toggle('active', card.dataset.username === username); }); CredentialManager.set(username, password); AuthState.reset(); Logger.info(`Selected user: ${username}`); } }; ``` -------------------------------- TITLE: Setup Button Event Listeners DESCRIPTION: Sets up event listeners for various buttons including 'resetAuthBtn', 'clearConsoleBtn', and 'updateEmailBtn'. It also includes a document-level click listener to handle requests to endpoints specified by 'data-endpoint' attributes. SOURCE: https://github.com/zio/zio-http/blob/main/zio-http-example/src/main/resources/digest-auth-client.html#_snippet_19 LANGUAGE: javascript CODE: ``` const resetBtn = DOM.get('resetAuthBtn'); if (resetBtn) { resetBtn.addEventListener('click', () => AuthState.reset()); } const clearBtn = DOM.get('clearConsoleBtn'); if (clearBtn) { clearBtn.addEventListener('click', () => { Logger.clear(); UI._clearTransactionDetails(); }); } const updateEmailBtn = DOM.get('updateEmailBtn'); if (updateEmailBtn) { updateEmailBtn.addEventListener('click', () => this._handleEmailUpdate()); } document.addEventListener('click', (e) => { if (e.target.closest('[data-endpoint]')) { const endpoint = e.target.closest('[data-endpoint]').dataset.endpoint; HTTPClient.makeRequest(endpoint); } }); ```