A ZIO HTTP “Hello, world” example with description and key points

Here’s a brief Scala ZIO HTTP “Hello, world” example from that repository, followed by a description of the code and “key points” to know about the example:

import zio.*
import zio.http.*

object HelloWorld extends ZIOAppDefault:

    // responds with plain text
    val homeRoute =
        Method.GET / Root -> handler(Response.text("Hello, World!"))

    // responds with JSON
    val jsonRoute =
        Method.GET / "json" -> handler(Response.json("""{"greetings": "Hello World!"}"""))

    // create HTTP route
    val app = Routes(homeRoute, jsonRoute)

    // run it like any simple app
    override val run = Server.serve(app)
                             .provide(Server.default)

Description

This source code example comes from this Github url.

This example is about the simplest-possible ZIO HTTP server example you can create in Scala. Here’s what it does:

  1. Defines two routes:

    • A home route (/) that responds to GET requests with plain text "Hello, World!"
    • A JSON route (/json) that responds to GET requests with a JSON greeting

  2. Combines these routes into a single app using Routes

  3. Runs the server using ZIO’s built-in server functionality with default settings

When running, this server will handle:

  • GET requests to / returning "Hello, World!" as plain text
  • GET requests to /json returning {"greetings": "Hello World!"} as JSON

It’s a minimal example showing ZIO HTTP’s declarative routing system and its support for different response types. The code uses ZIO’s effect system for managing side effects and dependencies.

Keys to know

Here are the key points to understand about this ZIO HTTP example:

  1. Functional Style

    • Uses ZIO’s functional effects system
    • Pure functions and immutable values throughout
    • Side effects are managed through ZIO effects
  2. Routing Pattern

    • Routes are defined using a simple DSL: Method.GET / "path"
    • Multiple routes can be combined using Routes(route1, route2)
    • Path segments are type-safe and composable
  3. Response Types

    • Shows two common response types: text() and json()
    • Responses are handled through the handler function
    • Type-safe response creation
  4. Application Structure

    • Extends ZIOAppDefault for easy bootstrapping
    • Uses dependency injection via provide(Server.default)
    • Clear separation between route definition and server setup
  5. Minimal Boilerplate

    • Concise, readable syntax for defining web services
    • No need for explicit threading or resource management
    • Server configuration is handled through sensible defaults

This example demonstrates ZIO HTTP’s focus on type safety, functional programming, and developer ergonomics while keeping the code straightforward.