From zio-skills
Use when asked to refactor routes to use the Endpoint API, convert imperative handlers to typed endpoints, use type-safe endpoints, or modernize ZIO HTTP routes. Teaches the pattern for moving from imperative route handlers to the declarative, type-driven Endpoint API.
How this skill is triggered — by the user, by Claude, or both
Slash command
/zio-skills:zio-http-imperative-to-declarativeThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
Use this skill when a user asks to:
Use this skill when a user asks to:
Imperative route handlers require manual extraction of request data and mapping to responses:
val routes = Routes(
Method.GET / "api" / "books" / string("id") -> handler { (req: Request) =>
val id = req.pathParam("id")
val limit = req.queryOrElse[Int]("limit", 10)
if (id.isEmpty) {
Response.status(Status.BadRequest)
} else {
Response.json(s"""{"id":"$id","limit":$limit}""")
}
}
)
Problems:
The Endpoint API separates what your API looks like from how it works:
val getBooks = Endpoint(Method.GET / "api" / "books" / string("id"))
.query(HttpCodec.query[Int]("limit"))
.out[BooksResponse](Status.Ok)
.outError[BadRequest](Status.BadRequest)
.implement { (id: String, limit: Int) =>
// Handler logic here — types are guaranteed
ZIO.succeed(BooksResponse(id, limit))
}
Benefits:
EndpointExecutorFirst, create typed models for request/response data:
import zio.schema._
case class Book(
@description("Book ID")
id: String,
@description("Book title")
title: String,
@description("Author name")
author: String
) derives Schema
case class CreateBookRequest(
title: String,
author: String
) derives Schema
case class BadRequest(error: String) derives Schema
case class NotFound(id: String) derives Schema
Key point: Use derives Schema to automatically generate ZIO Schema for your types. This powers type-safe codecs.
Create an object holding all your endpoint declarations (no logic yet):
import zio.http._
import zio.http.endpoint._
object BookEndpoints {
// GET /api/books/:id?limit=10
val getBook = Endpoint(Method.GET / "api" / "books" / string("id"))
.query(HttpCodec.query[Int]("limit").optional)
.out[Book](Status.Ok)
.outError[NotFound](Status.NotFound)
// POST /api/books
val createBook = Endpoint(Method.POST / "api" / "books")
.in[CreateBookRequest]
.out[Book](Status.Created)
.outError[BadRequest](Status.BadRequest)
// DELETE /api/books/:id
val deleteBook = Endpoint(Method.DELETE / "api" / "books" / string("id"))
.out[Unit](Status.NoContent)
.outError[NotFound](Status.NotFound)
}
Key types:
Endpoint(...) — starts a new endpoint with a route pattern.query(...) — adds a typed query parameter.in[T] — request body type (must have Schema[T]).out[T](Status.X) — response body type and HTTP status.outError[E](Status.Y) — error type and status (can chain multiple)Now bind business logic to your declared endpoints:
import zio._
object BookService {
def getBook(id: String, limit: Option[Int]): IO[NotFound, Book] =
if (id == "42") {
ZIO.succeed(Book("42", "The Answer", "Douglas Adams"))
} else {
ZIO.fail(NotFound(id))
}
def createBook(req: CreateBookRequest): IO[BadRequest, Book] =
if (req.title.isEmpty) {
ZIO.fail(BadRequest("Title is required"))
} else {
ZIO.succeed(Book("999", req.title, req.author))
}
def deleteBook(id: String): IO[NotFound, Unit] =
if (id == "42") {
ZIO.succeed(())
} else {
ZIO.fail(NotFound(id))
}
}
Now wire handlers:
val routes = Routes(
BookEndpoints.getBook.implement { (id: String, limit: Option[Int]) =>
BookService.getBook(id, limit)
},
BookEndpoints.createBook.implement { (req: CreateBookRequest) =>
BookService.createBook(req)
},
BookEndpoints.deleteBook.implement { (id: String) =>
BookService.deleteBook(id)
}
)
Key insight: The handler receives typed parameters that exactly match your endpoint declaration. The framework handles serialization/deserialization automatically.
import zio.http.endpoint.openapi._
object BookAPI extends ZIOAppDefault {
val routes = Routes(
BookEndpoints.getBook.implement { /* ... */ },
BookEndpoints.createBook.implement { /* ... */ },
BookEndpoints.deleteBook.implement { /* ... */ }
)
// Bonus: auto-generate OpenAPI documentation
val openAPI = OpenAPIGen.fromEndpoints(
title = "Book Store API",
version = "1.0.0",
endpoints = List(
BookEndpoints.getBook,
BookEndpoints.createBook,
BookEndpoints.deleteBook
)
)
val allRoutes = routes ++ SwaggerUI.routes("docs", openAPI)
def run = Server.serve(allRoutes).provide(Server.default)
}
val routes = Routes(
Method.POST / "api" / "books" -> handler { (req: Request) =>
// Manual extraction
val bodyStr <- req.body.asString
val json = ujson.read(bodyStr)
val title = json("title").str
val author = json("author").str
if (title.isEmpty) {
Response.status(Status.BadRequest)
} else {
val book = Book("999", title, author)
Response.json(ujson.write(book))
}
}
)
Problems:
object BookEndpoints {
val createBook = Endpoint(Method.POST / "api" / "books")
.in[CreateBookRequest]
.out[Book](Status.Created)
.outError[BadRequest](Status.BadRequest)
}
val routes = Routes(
BookEndpoints.createBook.implement { (req: CreateBookRequest) =>
if (req.title.isEmpty) {
ZIO.fail(BadRequest("Title required"))
} else {
ZIO.succeed(Book("999", req.title, req.author))
}
}
)
Benefits:
val getBook = Endpoint(Method.GET / "api" / "books" / int("id"))
.out[Book](Status.Ok)
val routes = Routes(
getBook.implement { (id: Int) => // id is Int, not String
ZIO.succeed(Book(id.toString, "Title", "Author"))
}
)
Supported extractors: int(...), string(...), long(...), uuid(...), trailing.
val search = Endpoint(Method.GET / "api" / "books")
.query(HttpCodec.query[String]("title").optional)
.query(HttpCodec.query[Int]("page").optional)
.query(HttpCodec.query[Int]("limit").optional)
.out[Chunk[Book]](Status.Ok)
val routes = Routes(
search.implement { (title: Option[String], page: Option[Int], limit: Option[Int]) =>
// All parameters are typed and optional
ZIO.succeed(Chunk.empty)
}
)
val getSecretBooks = Endpoint(Method.GET / "api" / "books" / "secret")
.auth(AuthType.Bearer) // Require Bearer token
.out[Chunk[Book]](Status.Ok)
.outError[Unauthorized](Status.Unauthorized)
val routes = Routes(
getSecretBooks.implement { (token: String) =>
// Token is automatically extracted from Authorization header
if (validateToken(token)) {
ZIO.succeed(Chunk.empty)
} else {
ZIO.fail(Unauthorized())
}
}
)
val customHeader = Endpoint(Method.GET / "api" / "books")
.header(HeaderCodec.custom("X-Custom-Header"))
.out[Chunk[Book]](Status.Ok)
val routes = Routes(
customHeader.implement { (customValue: String) =>
ZIO.succeed(Chunk.empty)
}
)
When converting an imperative route to declarative:
derives SchemaEndpoint(...) declaration with route pattern.query(...) for each query parameter.in[RequestType] for request body.out[ResponseType](Status.X) for success response.outError[ErrorType](Status.Y) for each error caseOpenAPIGen.fromEndpointsEndpoint[PathInput, Input, Err, Output, Auth] — fully typed endpoint descriptionHttpCodec — codec for query params, headers, bodiesAuthType — authentication requirement (None, Basic, Bearer, Digest, Custom, Or)handler(...) — converts a function to a Handler.implement(...) — binds a handler to an endpointEndpointExecutor to call typed endpointsDoc.p(...) for OpenAPI (see zio-http-endpoint-to-openapi)@@zio-http-testkit without spinning up a server| Symptom | Likely cause | Fix |
|---|---|---|
not found: type Schema or Schema[T] | Missing zio-schema dep or missing DeriveSchema.gen for case class. | Add "dev.zio" %% "zio-schema-derivation"; implicit val schema: Schema[T] = DeriveSchema.gen for each type. |
value implement is not a member of Endpoint[...] | Imperative-style binding used; Endpoint expects a typed handler. | Use endpoint.implement { case (path, query) => ... }. The lambda must match the endpoint's input arity. |
Compile error: lambda parameter count mismatch | Handler arity doesn't match the endpoint's typed input. | An endpoint with Method.GET / "x" / int("id") plus .query(...) produces (Int, Option[Q]) => …. |
| Endpoint compiles but returns 404 at runtime | Routes object built from endpoints not bound to the server, or path typo. | Pass Routes(...) to Server.serve(...); verify the endpoint's path string matches the request URL. |
Migration leaves an unused Request => Response handler somewhere | Imperative residue not removed during refactor. | Search for handler { blocks and confirm each is either deleted or paired with a typed endpoint via .implement. |
references/examples/BookEndpointsApp.scala — combines the snippets shown across Steps 2–4 into a single runnable file (data types, endpoint declarations, service logic, routes, OpenAPI + Swagger UI). Read this first when you want a copy-paste starting point instead of stitching the snippets together.Provides behavioral guidelines to reduce common LLM coding mistakes, focusing on simplicity, surgical changes, assumption surfacing, and verifiable success criteria.
Searches, retrieves, and installs Agent Skills from prompts.chat registry using MCP tools like search_skills and get_skill. Activates for finding skills, browsing catalogs, or extending Claude.
Creates, edits, and optimizes skills for Claude Code, including drafting, evaluating with test prompts, iterating on performance, and improving skill descriptions for better triggering accuracy.
npx claudepluginhub zio/zio-skills --plugin zio-skills