================ LIBRARY RULES ================ - Ignore anything with the term `printSource`. ================ CODE SNIPPETS ================ TITLE: GET /resources - Custom Output Codec DESCRIPTION: This example illustrates using `Endpoint#outCodec` to provide a custom `HttpCodec` for defining output properties. This offers more granular control, such as selectively adding headers to specific outputs. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_32 LANGUAGE: APIDOC CODE: ``` ## GET /resources (Custom Output Codec) ### Description This endpoint returns either an Article (with a Date header) or a Book, using a custom HttpCodec for output definition, allowing for selective header application. ### Method GET ### Endpoint /resources ### Parameters None ### Request Body None ### Response #### Success Response (200) - **Either[(Article, Header.Date), Book]** - Represents a response that can be either an Article with a Date header, 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. - **Header.Date** - The date header, applied specifically to the Article response. #### Response Example (Article) ```json { "title": "Understanding ZIO HTTP", "author": "Jane Doe" } ``` #### Headers (for Article response) - **Date**: [RFC 7231 formatted date string] #### Response Example (Book) ```json { "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams" } ``` ``` -------------------------------- 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: Rendering a PathCodec to a String DESCRIPTION: Demonstrates how to convert a PathCodec into its string representation using the render or toString methods. This provides a textual view of the path structure. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_4 LANGUAGE: scala CODE: ``` pathCodec.render pathCodec.toString ``` -------------------------------- 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: 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: GET /resources - Multiple Output Types (Union Type - Scala 3) DESCRIPTION: This endpoint uses Scala 3's union types with `Endpoint#orOut` to define multiple possible output types for a single endpoint, offering a more concise syntax than `Either`. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_29 LANGUAGE: APIDOC CODE: ``` ## GET /resources (Multiple Output Types - Union Type) ### Description This endpoint returns either a Course or a Quiz, defined using Scala 3's union types. ### Method GET ### Endpoint /resources ### Parameters None ### Request Body None ### Response #### Success Response (200) - **Course | Quiz** - Represents a response that can be either a Course or a Quiz. - **Course**: - **title** (string) - The title of the course. - **price** (double) - The price of the course. - **Quiz**: - **question** (string) - The quiz question. - **level** (integer) - The difficulty level of the quiz. #### Response Example (Quiz) ```json { "question": "What is the boiling point of water in Celsius?", "level": 2 } ``` #### Response Example (Course) ```json { "title": "Introduction to Programming", "price": 49.99 } ``` ``` -------------------------------- TITLE: Serve Static Resources from Classpath with ZIO HTTP DESCRIPTION: Illustrates serving static files embedded within the application's classpath using ZIO HTTP's `Middleware.serveResources`. This is commonly used for serving assets packaged with the application, such as those in a `src/main/resources` directory. It simplifies deployment by including static assets directly in the JAR file. Dependencies are handled by the build tool (e.g., sbt, Maven). SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/aop/middleware.md#_snippet_20 LANGUAGE: scala CODE: ``` import zio.http.middleware.Middleware import zio.http.Server val staticResourcesApp = Server.serve(Middleware.serveResources("public")) .provide(Server.default) ``` -------------------------------- TITLE: Rendering PathCodecs DESCRIPTION: Render a PathCodec to its string representation using `render` or `toString` to see the expected path pattern. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_10 LANGUAGE: APIDOC CODE: ``` ## Rendering PathCodecs To visualize the path pattern that a `PathCodec` matches, you can render it to a string. ```scala // Assuming pathCodec is defined as: empty / "users" / int("user-id") / "posts" / string("post-id") val renderedPath: String = pathCodec.render // renderedPath will be "/users/{user-id}/posts/{post-id}" val pathAsString: String = pathCodec.toString // pathAsString will also be "/users/{user-id}/posts/{post-id}" ``` ``` -------------------------------- TITLE: GET /resources - Output Headers with Multiple Outputs (Conditional) DESCRIPTION: This example shows how to conditionally add output headers to specific response types when multiple outputs are defined. The 'Date' header is applied only to the 'Article' output. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_30 LANGUAGE: APIDOC CODE: ``` ## GET /resources (Conditional Output Headers) ### Description This endpoint returns either an Article (with a Date header) or a Book. The Date header is specifically applied to the Article response. ### 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. - **Date** (Header) - The date the article was published or generated. - **Book**: - **title** (string) - The title of the book. - **author** (string) - The author of the book. #### Response Example (Article) ```json { "title": "Understanding ZIO HTTP", "author": "Jane Doe" } ``` #### Headers (for Article response) - **Date**: [RFC 7231 formatted date string] #### Response Example (Book) ```json { "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams" } ``` ``` -------------------------------- TITLE: GET /resources - Multiple Output Types (Either) DESCRIPTION: This endpoint demonstrates how to handle multiple, distinct output types for a single endpoint. It returns either a Course or a Quiz based on a random condition. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_28 LANGUAGE: APIDOC CODE: ``` ## GET /resources (Multiple Output Types) ### Description This endpoint returns either a Course or a Quiz. The specific response type is determined at runtime. ### Method GET ### Endpoint /resources ### Parameters None ### Request Body None ### Response #### Success Response (200) - **Either[Quiz, Course]** - Represents a response that can be either a Quiz or a Course. - **Quiz**: - **question** (string) - The quiz question. - **level** (integer) - The difficulty level of the quiz. - **Course**: - **title** (string) - The title of the course. - **price** (double) - The price of the course. #### Response Example (Quiz) ```json { "question": "What is the boiling point of water in Celsius?", "level": 2 } ``` #### Response Example (Course) ```json { "title": "Introduction to Programming", "price": 49.99 } ``` ``` -------------------------------- TITLE: GET /books - Describing Output Properties DESCRIPTION: This endpoint demonstrates how to describe the output properties of a success response using `Endpoint#out`. It takes a query parameter 'q' and returns a list of Book objects. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_26 LANGUAGE: APIDOC CODE: ``` ## GET /books ### Description This endpoint retrieves a list of books based on a query parameter 'q'. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **q** (string) - Required - The query parameter to filter books. ### Request Body None ### Response #### Success Response (200) - **List[Book]** - A list of book objects. - **title** (string) - The title of the book. - **author** (string) - The author of the book. #### Response Example ```json [ { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" }, { "title": "To Kill a Mockingbird", "author": "Harper Lee" } ] ``` ``` -------------------------------- TITLE: Create HTML from String using zio-http DESCRIPTION: Generates an Html instance directly from a String. This method is simple but lacks compile-time checks for HTML validity. It's useful for quick generation but can lead to runtime errors if the HTML is malformed. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/template.md#_snippet_0 LANGUAGE: scala CODE: ``` import zio.http.template._ val divHtml1: Html = Html.fromString("
ZIO Homepage
") ``` -------------------------------- TITLE: Complete ZIO HTTP Route with Value Object Codec (Scala) DESCRIPTION: A full ZIO HTTP application example demonstrating the use of a custom `UserId` value object codec within routes. It showcases how `transformOrFailLeft` is used to create a `PathCodec` for `UserId` and how routes handle this custom type, including custom error handling for invalid user IDs. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_15 LANGUAGE: Scala CODE: ``` import zio._ import zio.http._ import zio.Cause.{Die, Stackless} import zio.http.codec.PathCodec object Main extends ZIOAppDefault { import zio.http.codec.PathCodec import PathCodec._ case class UserId private (value: Int) object UserId { def apply(value: Int): Either[String, UserId] = if (value > 0) Right(new UserId(value)) else Left("User id must be greater than zero") } val userId: PathCodec[UserId] = int("user-id").transformOrFailLeft(UserId.apply)(_.value) val routes: Routes[Any, Response] = Routes( Method.GET / "users" / userId -> Handler.fromFunctionHandler[(UserId, Request)] { case (userId: UserId, request: Request) => Handler.text(userId.value.toString) }, ).handleErrorCause { case Stackless(cause, _) => cause match { case Die(value, _) => if (value.getMessage == "User id must be greater than zero") Response.badRequest(value.getMessage) else Response.internalServerError } } def run = Server.serve(routes).provide(Server.default) ``` -------------------------------- TITLE: Creating an HTML Response Using Template DESCRIPTION: Demonstrates how to use ZIO HTTP's built-in templating to create simple HTML pages with dynamic content. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/handler.md#_snippet_31 LANGUAGE: APIDOC CODE: ``` ## GET /hello ### Description Creates a simple HTML page with a "Hello world!" title and a "This is a simple HTML page." paragraph. ### Method GET ### Endpoint /hello ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Content-Type**: text/html - **Body**: HTML content #### Response Example ```html ZIO HTTP - Hello world!

Hello world!

This is a simple Hello, World! HTML page.

``` ``` -------------------------------- 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: Building PathCodecs with Combinators DESCRIPTION: Demonstrates constructing complex PathCodecs by combining predefined codecs using the '/' operator. The resulting codec's type reflects the combined segment types. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_1 LANGUAGE: scala CODE: ``` import zio.http.codec.PathCodec import PathCodec._ val pathCodec = empty / "users" / int("user-id") / "posts" / string("post-id") ``` -------------------------------- TITLE: Composable URLs DESCRIPTION: Demonstrates how to configure a base URL for a client and make relative requests. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_15 LANGUAGE: APIDOC CODE: ``` ## Composable URLs In ZIO HTTP, URLs are composable. This means that if we have two URLs, we can combine them to create a new URL. This is useful when we want to prevent duplication of the base URL in our code. For example, assume we have a base URL `http://localhost:8080` and we want to make several requests to different endpoints and query parameters under this base URL. We can configure the client with this URL using the `Client#url` and then every request will be made can be relative to this base URL: ```scala mdoc:compile-only import zio._ import zio.http._ import zio.schema.DeriveSchema import zio.schema.codec.JsonCodec.schemaBasedBinaryCodec case class User(name: String, age: Int) object User { implicit val schema = DeriveSchema.gen[User] } val program: ZIO[Client, Throwable, Unit] = for { client <- ZIO.serviceWith[Client](_.url(url"http://localhost:8080").batched) _ <- client.post("/users")(Body.from(User("John", 42))) res <- client.get("/users") _ <- client.delete("/users/1") _ <- res.body.asString.debug } yield () ``` The following methods are available for setting the base URL: | Method Signature | Description | |---------------------------------|------------------------------------------------| | `Client#url(url: URL)` | Sets the URL directly. | | `Client#uri(uri: URI)` | Sets the URL from the provided URI. | | `Client#path(path: String)` | Sets the path of the URL from a string. | | `Client#path(path: Path)` | Sets the path of the URL from a `Path` object. | | `Client#port(port: Int)` | Sets the port of the URL. | | `Client#scheme(scheme: Scheme)` | Sets the scheme (protocol) for the URL. | The `Scheme` is a sealed trait that represents the different schemes (protocols) that can be used in a request. The available schemes are `HTTP` and `HTTPS` for HTTP requests, and `WS` and `WSS` for WebSockets. Here is the list of methods that are available for adding URL, Path, and QueryParams to the client's configuration: | Methods | Description | |----------------------------------------------------|------------------------------------------------------------------------| | `Client#addUrl(url: URL)` | Adds another URL to the existing one. | | `Client#addPath(path: String)` | Adds a path segment to the URL. | | `Client#addPath(path: Path)` | Adds a path segment from a `Path` object to the URL. | | `Client#addLeadingSlash` | Adds a leading slash to the URL path. | | `Client#addTrailingSlash` | Adds a trailing slash to the URL path. | | `Client#addQueryParam(key: String, value: String)` | Adds a query parameter with the specified key-value pair to the URL. | | `Client#addQueryParams(params: QueryParams)` | Adds multiple query parameters to the URL from a `QueryParams` object. | ``` -------------------------------- TITLE: Custom Output Codec for Conditional Headers in Zio HTTP DESCRIPTION: This snippet demonstrates using 'Endpoint#outCodec' to provide a custom HttpCodec for output, allowing for more control over output properties such as conditionally adding headers to specific output types. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_25 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ import zio.http.endpoint._ import zio.schema._ case class Book(title: String, author: String) object Book { implicit val schema: Schema[Book] = DeriveSchema.gen } case class Article(title: String, author: String) object Article { implicit val schema: Schema[Article] = DeriveSchema.gen } val endpoint: Endpoint[Unit, Unit, ZNothing, Either[(Article, Header.Date), Book], AuthType.None] = ``` -------------------------------- TITLE: GET /resources DESCRIPTION: Defines an endpoint that returns either an Article and Date, or a Book and Date. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_36 LANGUAGE: APIDOC CODE: ``` ## GET /resources ### Description This endpoint retrieves resources, returning either Article details with a date or Book details with a date. ### Method GET ### Endpoint /resources ### Parameters ### Request Body ### Request Example (No request body defined for this GET endpoint) ### Response #### Success Response (200) - **(Article, Header.Date)** or **(Book, Header.Date)** - The resource details and associated date. #### Response Example ```json { "title": "Example Article Title", "author": "Article Author", "date": "2023-10-27T10:00:00Z" } ``` OR ```json { "title": "Example Book Title", "author": "Book Author", "date": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- TITLE: Creating a Form DESCRIPTION: Provides methods for constructing `Form` data from various sources. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/form.md#_snippet_13 LANGUAGE: APIDOC CODE: ``` ## Creating a Form ### Description The `Form`'s companion object offers several convenient methods for constructing form data, whether from individual form fields, key-value pairs, multipart bytes, query parameters, or URL-encoded data. ``` LANGUAGE: APIDOC CODE: ``` ### Creating an Empty Form #### Constructor We can create an empty form using the `Form.empty` method: ```scala mdoc:compile-only import zio.http._ val emptyForm = Form.empty ``` This creates an empty form with no fields. ``` LANGUAGE: APIDOC CODE: ``` ### Creating a Form from Form Fields #### Constructor We can create a form by providing individual form fields using the `Form.apply` method. This method takes one or more `FormField` objects: ```scala mdoc:compile-only import zio.http._ val form = Form( FormField.Simple("name", "John"), FormField.Simple("age", "42"), ) ``` ``` LANGUAGE: APIDOC CODE: ``` ### Creating a Form from Key-Value Pairs #### Constructor We can create a form from key-value pairs using the `Form.fromStrings` method: ```scala mdoc:compile-only import zio.http._ val formData = Form.fromStrings( "username" -> "johndoe", "password" -> "secret", ) ``` ``` -------------------------------- TITLE: Render Composed HTML Flash Messages in Scala DESCRIPTION: Illustrates how to retrieve and render composed HTML flash messages (notice and alert) using ZIO HTTP's Flash utilities. It employs `foldHtml` to apply different rendering functions based on whether a notice or alert message is present, composing them into a single HTML output. This allows for conditional styling or presentation of different message types. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/headers/session/flash.md#_snippet_20 LANGUAGE: scala CODE: ``` val getBoth: Flash[Html] = Flash.getMessageHtml.foldHtml(renderNotice, renderAlert)(renderBothMessage) val html = request.flash(getBoth).getOrElse(renderNoFlash) ``` -------------------------------- TITLE: GET /books - Output with Custom Header DESCRIPTION: This endpoint shows how to add a custom 'Date' header to the output of a success response. It still takes a query parameter 'q' and returns a list of Book objects. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/endpoint.md#_snippet_27 LANGUAGE: APIDOC CODE: ``` ## GET /books (with Date Header) ### Description This endpoint retrieves a list of books based on a query parameter 'q' and includes a custom 'Date' header in the response. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **q** (string) - Required - The query parameter to filter books. ### Request Body None ### Response #### Success Response (200) - **List[Book]** - A list of book objects. - **title** (string) - The title of the book. - **author** (string) - The author of the book. - **Header.Date** - The date header. #### Response Example ```json [ { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" } ] ``` #### Headers - **Date**: [RFC 7231 formatted date string] ``` -------------------------------- TITLE: Attaching Documentation to PathCodec DESCRIPTION: Explains the use of the PathCodec#?? operator to attach documentation (Doc) to a PathCodec. This is valuable for generating API documentation. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_5 LANGUAGE: scala CODE: ``` import zio.http.codec._ val users = PathCodec.literal("users") ?? (Doc.p("Managing users including CRUD operations")) ``` -------------------------------- TITLE: GET /books?id= (Declarative Style) DESCRIPTION: A declarative implementation of the bookstore API endpoint using ZIO HTTP's Endpoint API. It separates API definition from implementation, abstracting away low-level request/response handling. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/http-codec.md#_snippet_39 LANGUAGE: APIDOC CODE: ``` ## GET /books?id= ### Description Retrieves a book from the bookstore using a declarative approach. The API definition is separate from the implementation logic. ### 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: Create Identity HandlerAspect with Output Context (Scala) DESCRIPTION: Demonstrates creating a basic HandlerAspect that passes a predefined integer value as output context. The `identity` aspect forwards the request and response unchanged, while `as(42)` injects the integer 42 into the context. This context can then be accessed by the handler. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/aop/handler_aspect.md#_snippet_12 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ val intAspect: HandlerAspect[Any, Int] = HandlerAspect.identity.as(42) ``` -------------------------------- TITLE: Define Simple Form Field - Scala DESCRIPTION: Defines the `Simple` case class, a subtype of `FormField`, for simple key-value pairs where the value is a String. It has a default content type of `MediaType.text.plain` and no filename. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/form.md#_snippet_2 LANGUAGE: scala CODE: ``` final case class Simple(name: String, value: String) extends FormField { override val contentType: MediaType = MediaType.text.plain override val filename: Option[String] = None } ``` -------------------------------- 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: UI Rendering Functions for Flash Messages in Scala DESCRIPTION: Provides HTML rendering functions for displaying flash messages (notice, alert) or no message. It also includes a function to render a list of users in an HTML table. These functions are used by the ZIO HTTP endpoints. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/headers/session/flash.md#_snippet_3 LANGUAGE: scala CODE: ``` object ui { def renderNoFlash = Html.fromString("no-flash") def renderBothMessage(notice: Html, alert: Html): Html = notice ++ alert def renderNotice(html: Html): Html = div(styleAttr := "background: green", html) def renderAlert(html: Html): Html = div(styleAttr := "background: red", html) def renderUsers(users: List[User]): Html = { table( borderAttr := "1", tHead( tr( th("Name"), th("Age"), ), ), tBody( ol(users.map { u => tr( td(u.name), td(u.age.toString), ) }), ), ) } } ``` -------------------------------- TITLE: Pattern Matching on WebSocketFrame DESCRIPTION: Demonstrates how to perform exhaustive pattern matching on WebSocketFrame types. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/socket/websocketframe.md#_snippet_14 LANGUAGE: APIDOC CODE: ``` ## Pattern Matching on WebSocketFrame ### Description Shows how to use pattern matching to handle different types of WebSocket frames. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example ```scala val frame: WebSocketFrame = ... frame match { case WebSocketFrame.Binary(bytes) => ??? case WebSocketFrame.Text(text) => ??? case WebSocketFrame.Close(status, reason) => ??? case WebSocketFrame.Ping => ??? case WebSocketFrame.Pong => ??? case WebSocketFrame.Continuation(buffer) => ??? } ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- TITLE: Transform PathCodec to Value Object (Scala) DESCRIPTION: Demonstrates transforming a ZIO HTTP PathCodec for integers into a custom `UserId` value object. This approach enforces domain constraints at the type level, improving code safety and expressiveness. It utilizes the `transform` method for direct conversion. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_13 LANGUAGE: Scala CODE: ``` import zio.http.codec.PathCodec import PathCodec._ case class UserId private(value: Int) object UserId { def apply(value: Int): UserId = if (value > 0) new UserId(value) else throw new IllegalArgumentException("User id must be positive") } val userIdPathCodec: PathCodec[UserId] = int("user-id").transform(UserId.apply)(_.value) ``` -------------------------------- TITLE: Flash Message Getters Reference DESCRIPTION: A comprehensive list of all available methods for retrieving flash messages. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/headers/session/flash.md#_snippet_17 LANGUAGE: APIDOC CODE: ``` ## Flash Message Getters Reference This table lists all available methods for retrieving flash messages. | Method | Output | Description | |-------------------------------------|------------------|----------------------------------------------------------------| | `Flash.get[A: Schema](key: String)` | `Flash[A]` | Gets any flash value of type `A` with the given key `key`. | | `Flash.getString(key: String)` | `Flash[String]` | Gets a flash value of type `String` with the given key `key`. | | `Flash.getNotice[A: Schema]` | `Flash[A]` | Gets a flash value of type `A` associated with the notice key. | | `Flash.getAlert[A: Schema]` | `Flash[A]` | Gets a flash value of type `A` associated with the alert key. | | `Flash.getFloat(key: String)` | `Flash[Float]` | Gets a flash value of type `Float` with the given key `key`. | | `Flash.getDouble(key: String)` | `Flash[Double]` | Gets a flash value of type `Double` with the given key `key`. | | `Flash.getInt(key: String)` | `Flash[Int]` | Gets a flash value of type `Int` with the given key `key`. | ``` -------------------------------- TITLE: Composable URLs with ZIO HTTP Client DESCRIPTION: Demonstrates setting a base URL for the ZIO HTTP client and making relative requests. This approach helps in avoiding duplication of base URLs across multiple API calls. It requires the 'zio-http' and 'zio-schema' libraries. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_12 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ import zio.schema.DeriveSchema import zio.schema.codec.JsonCodec.schemaBasedBinaryCodec case class User(name: String, age: Int) object User { implicit val schema = DeriveSchema.gen[User] } val program: ZIO[Client, Throwable, Unit] = for { client <- ZIO.serviceWith[Client](_.url(url"http://localhost:8080").batched) _ <- client.post("/users")(Body.from(User("John", 42))) res <- client.get("/users") _ <- client.delete("/users/1") _ <- res.body.asString.debug } yield () ``` -------------------------------- TITLE: Process Streaming Multipart Form Data in Scala DESCRIPTION: Details how to process multipart form data using a streaming approach with `Body#asMultipartFormStream`. This allows handling large uploads efficiently by processing parts as they arrive. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/body.md#_snippet_26 LANGUAGE: scala CODE: ``` import zio.http.{Body, FormField, StreamingForm} import zio.Task // Assuming 'body' is an existing Body instance val streamingForm: Task[StreamingForm] = body.asMultipartFormStream val processedForm: Task[Unit] = streamingForm.flatMap { form => form.fields.flatMap { case FormField.Binary(name, data, contentType, transferEncoding, filename) => ??? // Handle binary field case FormField.StreamingBinary(name, contentType, transferEncoding, filename, data) => ??? // Handle streaming binary field case FormField.Text(name, value, contentType, filename) => ??? // Handle text field case FormField.Simple(name, value) => ??? // Handle simple field }.run(???) } ``` -------------------------------- TITLE: Using Value Objects with PathCodecs DESCRIPTION: Demonstrates how to transform a PathCodec into a more specific data type like a value object using the `transform` and `transformOrFailLeft` methods. This is useful for domain-driven design and type safety. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/routing/path_codec.md#_snippet_17 LANGUAGE: APIDOC CODE: ``` ## Using Value Objects with PathCodecs Other than the common `PathCodec` constructors, it's also possible to transform a `PathCodec` into a more specific data type using the `transform` method. This becomes particularly useful when adhering to domain-driven design principles and opting for value objects instead of primitive types: ```scala import zio.http.codec.PathCodec import PathCodec._ case class UserId private(value: Int) object UserId { def apply(value: Int): UserId = if (value > 0) new UserId(value) else throw new IllegalArgumentException("User id must be positive") } val userIdPathCodec: PathCodec[UserId] = int("user-id").transform(UserId.apply)(_.value) ``` This approach enables us to utilize the `UserId` value object in our routes, and the `PathCodec` will take care of the conversion between the path segment and the value object. In the previous example, instead of throwing an exception, we can model the failure using the `Either` data type and then use the `transformOrFailLeft` to create a `PathCodec`: ```scala import zio.http.codec.PathCodec import PathCodec._ case class UserId private(value: Int) object UserId { def apply(value: Int): Either[String, UserId] = if (value > 0) Right(new UserId(value)) else Left("User id must be positive") } val userIdPathCodec: PathCodec[UserId] = int("user-id").transformOrFailLeft(UserId.apply)(_.value) ``` Here is a list of the available transformation methods: ```scala trait PathCodec[A] { def transform[A2](f: A => A2)(g: A2 => A): PathCodec[A2] def transformOrFail[A2](f: A => Either[String, A2])(g: A2 => Either[String, A]): PathCodec[A2] def transformOrFailLeft[A2](f: A => Either[String, A2])(g: A2 => A): PathCodec[A2] def transformOrFailRight[A2](f: A => A2)(g: A2 => Either[String, A]): PathCodec[A2] } ``` Here is a complete example: ```scala import zio._ import zio.http._ import zio.Cause.{Die, Stackless} import zio.http.codec.PathCodec object Main extends ZIOAppDefault { import zio.http.codec.PathCodec import PathCodec._ case class UserId private (value: Int) object UserId { def apply(value: Int): Either[String, UserId] = if (value > 0) Right(new UserId(value)) else Left("User id must be greater than zero") } val userId: PathCodec[UserId] = int("user-id").transformOrFailLeft(UserId.apply)(_.value) val routes: Routes[Any, Response] = Routes( Method.GET / "users" / userId -> Handler.fromFunctionHandler[(UserId, Request)] { case (userId: UserId, request: Request) => Handler.text(userId.value.toString) }, ).handleErrorCause { case Stackless(cause, _) => cause match { case Die(value, _) => if (value.getMessage == "User id must be greater than zero") Response.badRequest(value.getMessage) else Response.internalServerError } } def run = Server.serve(routes).provide(Server.default) } ``` ``` -------------------------------- TITLE: Create Form from Key-Value Pairs - Scala DESCRIPTION: Demonstrates creating a `Form` from a sequence of key-value pairs using the `Form.fromStrings` method. This is a convenient way to quickly define textual form data. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/form.md#_snippet_10 LANGUAGE: scala CODE: ``` import zio.http._ val formData = Form.fromStrings( "username" -> "johndoe", "password" -> "secret", ) ``` -------------------------------- TITLE: Create HTML Response with Template DESCRIPTION: Demonstrates how to create a simple HTML response using ZIO HTTP's built-in templating system. This is useful for generating basic HTML pages with minimal effort. It requires importing `zio.http._` and `zio.http.template._`. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/handler.md#_snippet_26 LANGUAGE: scala CODE: ``` import zio.http._ import zio.http.template._ Routes( Method.GET / "hello" -> Handler.template("Hello world!")( html( body( p("This is a simple HTML page.") ) ) ) ) ``` -------------------------------- TITLE: Derive Schema for Custom Type DESCRIPTION: Automatically derives a `Schema[Book]` for a `Book` case class using ZIO Schema's `DeriveSchema.gen`. This simplifies codec generation by leveraging ZIO Schema's capabilities to infer the structure of the data type. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/body/binary_codecs.md#_snippet_1 LANGUAGE: scala CODE: ``` import zio.schema._ object Book { implicit val schema: Schema[Book] = DeriveSchema.gen[Book] } ``` -------------------------------- TITLE: Handler.fromFile and Handler.fromFileZIO DESCRIPTION: Constructs handlers that serve files directly from the server's file system. `fromFile` takes a `File` object, while `fromFileZIO` accepts a `ZIO` effect that yields a `File`. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/handler.md#_snippet_45 LANGUAGE: APIDOC CODE: ``` ## Handler.fromFile and Handler.fromFileZIO ### Description Used to create handlers that return a file from the server. ### Constructors - `Handler.fromFile(file: File)`: Creates a handler from a `File` object. - `Handler.fromFileZIO(zioFile: ZIO[R, Throwable, File])`: Creates a handler from a `ZIO` effect that returns a `File`. ### Request Example ```scala import zio.http._ import java.io.File Routes( Method.GET / "video" -> Handler.fromFile(new File("src/main/resources/TestVideoFile.mp4")), Method.GET / "text" -> Handler.fromFile(new File("src/main/resources/TestFile.txt")), ) ``` ``` -------------------------------- TITLE: Serve Static Files from Directory with ZIO HTTP DESCRIPTION: Demonstrates how to serve static files from a specified directory using ZIO HTTP's `Middleware.serveDirectory`. This middleware is useful for applications that need to serve assets like HTML, CSS, or JavaScript files directly from the file system. No external dependencies are required beyond ZIO HTTP itself. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/aop/middleware.md#_snippet_19 LANGUAGE: scala CODE: ``` import zio.http.middleware.Middleware import zio.http.Server val staticFilesApp = Server.serve(Middleware.serveDirectory("src/main/resources/public")) .provide(Server.default) ``` -------------------------------- 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: Customizing Debug Logging for Client Responses DESCRIPTION: Illustrates how to customize the output of the `ZClientAspect.debug` aspect by providing a partial function that formats the logged response information. This allows for more specific debugging data extraction from responses. It requires the 'zio-http' library. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/client.md#_snippet_14 LANGUAGE: scala CODE: ``` val debugResponse = ZClientAspect.debug { case res: Response => res.headers.mkString("\n") } val program = for { client <- ZIO.service[Client].map(_ @@ debugResponse) _ <- client.request(Request.get("http://jsonplaceholder.typicode.com/todos")) } yield () ``` -------------------------------- TITLE: Get Users Route with Flash Message Display in Scala DESCRIPTION: Defines a GET route for '/users' that retrieves a list of users and displays them. It also fetches and renders any available flash messages (notice or alert) before displaying the user list. SOURCE: https://github.com/zio/zio-http/blob/main/docs/reference/headers/session/flash.md#_snippet_5 LANGUAGE: scala CODE: ``` import zio._ import zio.http._ val getUsersRoute: Route[Ref[List[User]] with Flash.Backend, Nothing] = Method.GET / "users" -> handler { (req: Request) => for { flashBackend <- ZIO.service[Flash.Backend] usersDb <- ZIO.service[Ref[List[User]]] users <- usersDb.get usersHTML = ui.renderUsers(users) html <- flashBackend.flashOrElse( request = req, flash = Flash.getMessageHtml.foldHtml(ui.renderNotice, ui.renderAlert)(ui.renderBothMessage), )(ui.renderNoFlash) } yield Response.html(html ++ usersHTML) } ```