Skip to main content

How to Generate Endpoints from a Smithy Model

In this guide, we start from an API that is described in a Smithy model and end with a ZIO HTTP server that implements it. By the end, you will have a small bookstore service whose endpoints and data types come from a .smithy file through SmithyEndpointGen, and whose handlers are the only code written by hand.

We first generate code from a model held in a string with SmithyEndpointGen.fromString, to see what the generator produces and how it reports a broken model. Then we generate the same kind of code from a .smithy file with SmithyEndpointGen.fromFile, write it to Scala source files, and implement and serve the generated endpoints.

The Problem​

Teams that design their APIs in Smithy keep the model as the source of truth: it names every operation, its HTTP method and path, its inputs and outputs, and its errors. A ZIO HTTP server for that API needs the same information again, as Endpoint values and as case classes with a Schema for every structure.

Writing that code by hand means copying the model into Scala and keeping the copy up to date. For example, a hand-written version of one bookstore operation looks like this:

import zio.http._
import zio.http.endpoint._
import zio.schema._

// Copied by hand from bookstore.smithy
case class Book(id: String, title: String, author: String, publishedYear: Option[Int])
object Book {
implicit val schema: Schema[Book] = DeriveSchema.gen[Book]
}

case class BookNotFound(message: String)
object BookNotFound {
implicit val schema: Schema[BookNotFound] = DeriveSchema.gen[BookNotFound]
}

val getBook =
Endpoint(Method.GET / "books" / string("id"))
.out[Book]
.outError[BookNotFound](Status.NotFound)

Every operation and structure in the model needs code like this, and nothing checks the copy against the model. This one already disagrees with it: the model names the field published_year, but the case class sends it as publishedYear, so clients built from the model never see the year. The next change to the model, such as a new field or a different status code, has to be found and repeated by hand too.

The zio-http-gen module reads the model and writes this code for us. We regenerate it whenever the model changes, and write only the handlers.

Prerequisites​

The Smithy generator is part of the zio-http-gen module. The generated code itself needs only zio-http:

libraryDependencies ++= Seq(
"dev.zio" %% "zio-http" % "3.12.0",
"dev.zio" %% "zio-http-gen" % "3.12.0",
)

The generator has no sbt plugin: we call it from a small program, and the code it writes is compiled with the rest of the project. If the generator runs in a separate project or script, the application itself does not need zio-http-gen.

This guide assumes you know how to declare and implement an Endpoint. If not, read the Endpoint reference first. You don't need to know Smithy well: the model below uses only a few of its features, and each is explained where it appears.

The generator lives in the zio.http.gen.smithy package, and the code that renders and writes its output lives in zio.http.gen.scala:

import zio.http.gen.scala.CodeGen
import zio.http.gen.smithy.SmithyEndpointGen

Describe the API in a Smithy Model​

Our bookstore has three operations: get a book by its ID, search the books by author, and add a book. Here is the whole model:

zio-http-example/src/main/scala/example/smithy/bookstore.smithy
$version: "2"

namespace example.bookstore

service Bookstore {
version: "2026-12-01"
operations: [GetBook, SearchBooks, CreateBook]
}

@documentation("Returns the book with the given ID.")
@http(method: "GET", uri: "/books/{id}")
operation GetBook {
input: GetBookInput
output: Book
errors: [BookNotFound]
}

@documentation("Returns the books written by the given author.")
@http(method: "GET", uri: "/books")
operation SearchBooks {
input: SearchBooksInput
output: BookList
}

@documentation("Adds a book to the catalog.")
@http(method: "POST", uri: "/books", code: 201)
operation CreateBook {
input: CreateBookInput
output: Book
}

structure GetBookInput {
@required
@httpLabel
id: String
}

structure SearchBooksInput {
@required
@httpQuery("author")
author: String
}

structure CreateBookInput {
@required
title: String

@required
author: String

published_year: Integer
}

structure Book {
@required
id: String

@required
title: String

@required
author: String

published_year: Integer
}

list Books {
member: Book
}

structure BookList {
@required
books: Books
}

@error("client")
@httpError(404)
structure BookNotFound {
@required
message: String
}

The parts that matter to the generator are:

  • @http on an operation gives its method, its URI, and, with code, its success status. The generator only generates operations that have this trait.
  • input and output name the structures for the request and the response. They must be named structures; the generator does not read inline input := { ... } definitions.
  • Member traits on the input structure say where each member comes from. @httpLabel binds a member to a {label} in the URI, @httpQuery("name") to a query parameter, and the members without such a trait form the JSON request body.
  • errors lists the error structures an operation can return. Each needs @error, and @httpError sets its status code.
  • @required makes a structure member required. Members without it become Option fields.

Generate Code from a String with SmithyEndpointGen.fromString​

SmithyEndpointGen.fromString takes a model as Smithy IDL text and returns Either[String, Code.Files]. Code.Files is a description of Scala source files, not compiled endpoints: the generator writes code for us to compile, the same way the OpenAPI generator does in How to Generate Server and Client Code from an OpenAPI Spec.

To see what it produces, we give it a model with just one operation:

val getBookModel: String =
"""|$version: "2"
|namespace example.bookstore
|
|@http(method: "GET", uri: "/books/{id}")
|operation GetBook {
| input: GetBookInput
| output: Book
|}
|
|structure GetBookInput {
| @required
| @httpLabel
| id: String
|}
|
|structure Book {
| @required
| id: String
|
| @required
| title: String
|}
|""".stripMargin

CodeGen.renderedFiles turns the Code.Files into source text, keyed by the path of each file. It takes the base package for the generated code:

val generated = SmithyEndpointGen.fromString(getBookModel)

val sources: Either[String, Map[String, String]] =
generated.map(files => CodeGen.renderedFiles(files, "example.bookstore"))

The keys of the map are the paths of the generated files:

sources.map(_.keys.toList.sorted)
// res2: Either[String, List[String]] = Right(
// value = List(
// "Endpoints.scala",
// "component/Book.scala",
// "component/GetBookInput.scala"
// )
// )

The generator produces one file per structure, under component, and one Endpoints.scala file with an Endpoints object that holds one endpoint for each operation. The paths are relative to the base package: Endpoints.scala declares package example.bookstore, and the structure files declare package example.bookstore.component.

CodeGen.renderedFiles does not format the code. In the next section, CodeGen.writeFiles formats it with scalafmt when it writes the files, and we look at the generated code for the whole bookstore.

Read Validation Errors​

Before it generates anything, SmithyEndpointGen.fromString validates the model, and it returns a Left with every problem it found. Here the URI has a {id} label, but the input structure names its member bookId:

val brokenModel: String =
"""|$version: "2"
|namespace example.bookstore
|
|@http(method: "GET", uri: "/books/{id}")
|operation GetBook {
| input: GetBookInput
| output: Book
| errors: [BookNotFound]
|}
|
|structure GetBookInput {
| @required
| @httpLabel
| bookId: String
|}
|
|structure Book {
| @required
| title: String
|}
|""".stripMargin

The model also lists an error, BookNotFound, that it never defines. Every problem is reported with the shape it was found in and an error code. The label mismatch is reported twice, once for the operation and once for the member:

SmithyEndpointGen.fromString(brokenModel).left.foreach(println)
// Smithy model validation failed:
// Errors (3):
// - GetBook.errors: [UNDEFINED_SHAPE] Reference to undefined shape: BookNotFound
// - GetBook: [MISSING_PATH_PARAMETER] Path parameter 'id' in URI has no corresponding member in GetBookInput
// - GetBookInput.bookId: [PATH_PARAMETER_MISMATCH] Member 'bookId' has @httpLabel but is not in the URI path: /books/{id}

The parser skips text it does not recognize, and validation checks only the shapes it found. Text that is not Smithy at all, such as an empty string, therefore produces Right with no files, so a generator program should treat an empty Code.Files as an error:

SmithyEndpointGen.fromString("").map(_.files.isEmpty)
// res4: Either[String, Boolean] = Right(value = true)
tip

To generate code without validating the model, pass SmithyConfig.fast as the second argument of SmithyEndpointGen.fromString. SmithyConfig is in the same package as SmithyEndpointGen.

Generate Source Files from a .smithy File​

A real model lives in a file. SmithyEndpointGen.fromFile reads a .smithy file and returns the same Either[String, Code.Files] as SmithyEndpointGen.fromString, with a Left also when the file cannot be read. CodeGen.writeFiles then writes the files to disk:

import java.nio.file.Paths

val written =
SmithyEndpointGen.fromFile(Paths.get("src/main/smithy/bookstore.smithy")).map { files =>
CodeGen.writeFiles(
files,
basePath = Paths.get("src/main/scala/example/bookstore/generated"),
basePackage = "example.bookstore.generated",
scalafmtPath = Some(Paths.get(".scalafmt.conf")),
)
}

CodeGen.writeFiles returns the paths of the files it wrote, and needs three settings:

  • basePath is the folder for the generated files. The generator does not add package folders below it, so point it at the folder of the base package.
  • basePackage is the package of the Endpoints object; the data types go into its component subpackage.
  • scalafmtPath is the scalafmt configuration to format the files with. With None, the files are written unformatted.

CodeGen.writeFiles creates missing folders and overwrites existing files, so running the generator again after a change to the model replaces the old code. It does not delete files, though: when a structure is removed from the model, delete its file by hand, or clear the folder before generating.

SmithyEndpointGen.generateFromFile does both steps in one call. It takes the model file, then the same basePath, basePackage, and scalafmtPath as CodeGen.writeFiles:

import java.nio.file.Paths

val written =
SmithyEndpointGen.generateFromFile(
Paths.get("src/main/smithy/bookstore.smithy"),
Paths.get("src/main/scala/example/bookstore/generated"),
"example.bookstore.generated",
Some(Paths.get(".scalafmt.conf")),
)

When a model is split across several files, SmithyEndpointGen.fromDirectory and SmithyEndpointGen.generate do the same for every .smithy file in a folder and its subfolders, and merge them into one model.

Runnable version, which generates the bookstore code from bookstore.smithy: GenerateBookstoreEndpoints.scala
zio-http-example/src/main/scala/example/smithy/GenerateBookstoreEndpoints.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http-gen:3.12.0"
// Run from the repository root:
// scala-cli run zio-http-example/src/main/scala/example/smithy/GenerateBookstoreEndpoints.scala
// Or: sbt "zioHttpExample/runMain example.smithy.GenerateBookstoreEndpoints"

package example.smithy

import java.nio.file.Paths

import zio.http.gen.scala.CodeGen
import zio.http.gen.smithy.SmithyEndpointGen

/**
* Generate Endpoints from a Smithy Model — Generate Source Files from a
* `.smithy` File
*
* Reads `bookstore.smithy`, generates the endpoint and data type sources, and
* writes them, formatted with the repository's scalafmt configuration, to the
* `generated` folder next to this file. In this repository, run `sbt fmt`
* afterwards, so the imports of the generated files follow the scalafix rules
* of the build.
*/
object GenerateBookstoreEndpoints {

val modelFile = Paths.get("zio-http-example/src/main/scala/example/smithy/bookstore.smithy")
val outputDir = Paths.get("zio-http-example/src/main/scala/example/smithy/generated")

def main(args: Array[String]): Unit =
SmithyEndpointGen.fromFile(modelFile) match {
case Left(error) =>
System.err.println(error)
sys.exit(1)
case Right(files) =>
val written = CodeGen.writeFiles(
files,
basePath = outputDir,
basePackage = "example.smithy.generated",
scalafmtPath = Some(Paths.get(".scalafmt.conf")),
)
written.toList.map(_.toString).sorted.foreach(println)
}
}

For the bookstore model, the generator writes seven files. The Endpoints object holds one endpoint for each operation:

zio-http-example/src/main/scala/example/smithy/generated/Endpoints.scala
package example.smithy.generated

import zio.http._
import zio.http.codec._
import zio.http.endpoint._

import example.smithy.generated.component._

object Endpoints {
import zio.http._
import zio.http.endpoint._
import zio.http.codec._
import zio.schema.annotation.fieldName
@fieldName("SearchBooks") val searchBooks = Endpoint(Method.GET / "books")
.query(HttpCodec.query[String]("author"))
.in[Unit](name = "application/json", doc = md"""Returns the books written by the given author.""")
.out[BookList](status = Status.Ok, doc = md"""Returns the books written by the given author.""")

@fieldName("CreateBook") val createBook = Endpoint(Method.POST / "books")
.in[CreateBookInput](name = "application/json", doc = md"""Adds a book to the catalog.""")
.out[Book](status = Status.Created, doc = md"""Adds a book to the catalog.""")

@fieldName("GetBook") val getBook = Endpoint(Method.GET / "books" / string("id"))
.in[Unit](name = "application/json", doc = md"""Returns the book with the given ID.""")
.out[Book](status = Status.Ok, doc = md"""Returns the book with the given ID.""")
.outError[BookNotFound](status = Status.NotFound)

}

Each endpoint declares what its operation in the model says:

  • getBook reads the id label from the path, returns a Book, and returns a BookNotFound with status 404 Not Found, from the @httpError(404) trait.
  • searchBooks reads the author query parameter.
  • createBook reads a CreateBookInput as the JSON request body and returns 201 Created, from code: 201.

The @documentation text of each operation becomes the documentation of its input and output, which shows up in the OpenAPI document generated from the endpoints.

Each structure becomes a case class with a derived Schema. Here is Book:

zio-http-example/src/main/scala/example/smithy/generated/component/Book.scala
package example.smithy.generated.component

import zio.schema._
import zio.schema.annotation.fieldName

case class Book(
@fieldName("published_year") publishedYear: Option[Int],
author: String,
id: String,
title: String,
)
object Book {
implicit val codec: Schema[Book] = DeriveSchema.gen[Book]
}

The published_year member is not @required, so it is an Option[Int]. Its name is converted to the Scala convention, publishedYear, and the @fieldName annotation keeps published_year as its name in JSON. The fields are not in the order of the model, so build generated case classes with named arguments.

Implement and Serve the Generated Endpoints​

The generated code is ordinary source code: once it is compiled with the project, the endpoints are implemented like hand-written ones. We implement each endpoint with Endpoint#implement and serve the resulting routes:

zio-http-example/src/main/scala/example/smithy/BookstoreServer.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file generated
// Run from this folder: scala-cli run BookstoreServer.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.smithy.BookstoreServer"

package example.smithy

import zio._

import zio.http._

import example.smithy.generated.Endpoints
import example.smithy.generated.component._

/**
* Generate Endpoints from a Smithy Model — Implement and Serve the Generated
* Endpoints
*
* Implements the endpoints that `GenerateBookstoreEndpoints` generated from
* `bookstore.smithy`, keeps the books in a `Ref`, and serves them on port 8080.
*/
object BookstoreServer extends ZIOAppDefault {

def routes(books: Ref[Map[String, Book]]): Routes[Any, Response] =
Routes(
Endpoints.getBook.implement { (id: String) =>
books.get.flatMap { all =>
ZIO.fromOption(all.get(id)).orElseFail(BookNotFound(s"No book with ID $id"))
}
},
Endpoints.searchBooks.implement { (author: String) =>
books.get.map { all =>
BookList(Chunk.fromIterable(all.values.filter(_.author == author)))
}
},
Endpoints.createBook.implement { (input: CreateBookInput) =>
books.modify { all =>
val id = (all.size + 1).toString
val book = Book(id = id, title = input.title, author = input.author, publishedYear = input.publishedYear)
(book, all + (id -> book))
}
},
)

val initialBooks: Map[String, Book] =
Map("1" -> Book(id = "1", title = "Zionomicon", author = "John De Goes", publishedYear = None))

def run =
Ref.make(initialBooks).flatMap { books =>
Server.serve(routes(books)).provide(Server.default)
}
}

The function passed to Endpoint#implement takes the endpoint's input, which the generated declarations decide:

  • getBook takes the id from the path as a String. Its body is declared as Unit, so the id is the whole input. Its effect may fail with BookNotFound, the error type the model declares.
  • searchBooks takes the author query parameter as a String.
  • createBook takes the decoded CreateBookInput.

The handlers depend on the model only through the generated types. If the model changes, for example a new required field in CreateBookInput, we regenerate the code, and the compiler shows every handler that has to change.

With the server running, the endpoints answer as the model describes:

$ curl -i http://localhost:8080/books/1
HTTP/1.1 200 OK
content-type: application/json
content-length: 77

{"published_year":null,"author":"John De Goes","id":"1","title":"Zionomicon"}

$ curl -i http://localhost:8080/books/9
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 31

{"message":"No book with ID 9"}

$ curl -i -X POST http://localhost:8080/books \
-H 'content-type: application/json' \
-d '{"title":"Functional Programming in Scala","author":"Paul Chiusano","published_year":2014}'
HTTP/1.1 201 Created
content-type: application/json
content-length: 99

{"published_year":2014,"author":"Paul Chiusano","id":"2","title":"Functional Programming in Scala"}

$ curl -i "http://localhost:8080/books?author=Paul%20Chiusano"
HTTP/1.1 200 OK
content-type: application/json
content-length: 111

{"books":[{"published_year":2014,"author":"Paul Chiusano","id":"2","title":"Functional Programming in Scala"}]}

The missing book gets the 404 status and the JSON body of BookNotFound, and the new book gets 201 Created, as the model declares. The published_year field keeps its name from the model in every response, and an empty Option is written as null. A request without the author query parameter gets 400 Bad Request, because the parameter is part of the endpoint.

How the Model Maps to Generated Code​

The bookstore uses only part of what the generator reads. This table lists how the Smithy elements it supports turn into code:

SmithyGenerated code
operation with @httpOne endpoint in the Endpoints object, named after the operation in camel case
{label} in the @http URIA path segment codec of the label member's type, such as string("id")
Input member with @httpQuery("name")Endpoint#query(HttpCodec.query[T]("name")), a required query parameter even without @required
Input member with @httpHeader("name")A required header codec, even without @required
Other input members, or one with @httpPayloadThe request body: the whole input structure, or the @httpPayload member's type
code in @httpThe success status, 200 OK by default
errors and @httpError(n).outError[E](status = ...); an error without @httpError gets 500 Internal Server Error
structureA case class with a derived Schema; members without @required become Option
snake_case member nameA camel case field with @fieldName("snake_case")
list and mapChunk[T] and Map[K, V]
unionA sealed trait
enumA sealed trait with one case class per value; JSON uses the case name, not the value after =
timestamp, blob, documentjava.time.Instant, Chunk[Byte], zio.json.ast.Json

An @httpHeader member whose name is well known, such as Authorization, gets a typed HeaderCodec.<name>; any other name gets HeaderCodec.name[String]("name") with the name in lowercase.

The generator produces no code for operations without @http, for service and resource shapes, or for authentication traits. It adds no response header codec for @httpHeader members of output structures; such a member stays an ordinary field of the output case class and is written in the JSON body.

The query row explains a choice in the bookstore model: an @httpQuery member always becomes a required query parameter, so a parameter that clients may leave out is better kept out of the query, for example in the request body. The same holds for @httpHeader.

SmithyConfig.preserveFieldNames keeps member names as they are in the model, without the camel case conversion:

import zio.http.gen.smithy.SmithyConfig

val keepNames = SmithyEndpointGen.fromString(getBookModel, SmithyConfig.preserveFieldNames)

Pass it as the second argument of SmithyEndpointGen.fromString, SmithyEndpointGen.fromFile, or SmithyEndpointGen.fromDirectory, or as the last argument of SmithyEndpointGen.generate and SmithyEndpointGen.generateFromFile.

Running the Examples​

All runnable code from this guide is in zio-http-example/src/main/scala/example/smithy/, together with the model and the generated code in its generated folder. To run the server, run scala-cli run BookstoreServer.scala from that folder, or sbt "zioHttpExample/runMain example.smithy.BookstoreServer" from the repository root, and send it the curl requests above. To regenerate the code after changing bookstore.smithy, run sbt "zioHttpExample/runMain example.smithy.GenerateBookstoreEndpoints" from the repository root, then sbt fmt, which sorts the imports of the generated files the way the repository's scalafix rules expect.

Going Further​