Skip to main content

How to Generate Server and Client Code from an OpenAPI Spec

In this guide, we start from an OpenAPI spec file and end with a running ZIO HTTP server and a client for it, without writing a single endpoint definition by hand. The generator in zio-http-gen reads the spec and writes Scala code for it: one Endpoint value per operation and one case class per schema. We then implement those endpoints as server routes and call them through an EndpointExecutor.

We run the generator from an sbt sourceGenerators task, so the code is written again from the spec on every compile, and a change to the spec shows up as a compile error wherever the server or the client no longer fits it.

The Problem​

Some APIs start as a spec, not as code. Another team owns the OpenAPI file, or the API is designed spec-first and reviewed before anyone writes a handler. A Scala service then has to serve that API, or call it, exactly as the spec describes it.

Writing the matching endpoints by hand means reading the spec and copying every path, parameter, request body, response type and status code into Scala. For a spec with a few dozen operations that is hours of typing, and it does not stay correct: when the spec gains a parameter or renames a field, nothing in the Scala code notices. The mismatch shows up at run time, as a 400 response or a decoding failure in production.

Generating the code from the spec removes both problems. The spec stays the single source of truth, and the compiler checks the server and the client against the code generated from it.

note

This guide goes from a spec to code. To go the other way, and produce an OpenAPI spec from endpoints you wrote in Scala, see the From Routes to Declarative Endpoints tutorial.

Prerequisites​

The generator runs inside sbt, while sbt compiles the project, so its libraries go on the classpath of the build itself. In sbt, that classpath is set in project/plugins.sbt:

zio-http-example-openapi-codegen/project/plugins.sbt
// The generator runs inside sbt, so its libraries go on the build's own classpath.
libraryDependencies ++= Seq(
"dev.zio" %% "zio-http-gen" % "3.12.0",
"dev.zio" %% "zio-json-yaml" % "1.1.3",
)
  • zio-http-gen contains the generator: EndpointGen turns an OpenAPI document into a description of Scala code, and CodeGen writes that code to files.
  • zio-json-yaml reads a YAML spec. A JSON spec does not need it: OpenAPI.fromJson reads one with no extra library.

sbt 1.x compiles its build with Scala 2.12, and both libraries are published for Scala 2.12, so this works whatever Scala version the project itself uses.

The project needs only zio-http. The generated code uses ZIO Schema to derive its codecs, and zio-http already depends on it:

libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"

This guide assumes you know what an Endpoint is and how Endpoint#implement turns one into a route. If not, start with the From Routes to Declarative Endpoints tutorial or the Endpoint reference.

The Spec​

The examples use a small pet store API. It has three operations: list the pets, with a limit query parameter, create a pet from a JSON body, and get one pet by its id, which responds with a 404 and an error body when no pet has that id. We save it as src/main/openapi/petstore.yaml:

zio-http-example-openapi-codegen/src/main/openapi/petstore.yaml
openapi: 3.0.3
info:
title: Pet Store
version: 1.0.0
paths:
/pets:
get:
operationId: listPets
parameters:
- name: limit
in: query
required: false
schema:
type: integer
responses:
"200":
description: The pets in the store
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Pet"
post:
operationId: createPet
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/NewPet"
responses:
"201":
description: The created pet
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
/pets/{petId}:
get:
operationId: getPet
parameters:
- name: petId
in: path
required: true
schema:
type: integer
responses:
"200":
description: The pet
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
"404":
description: No pet has this id
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
type: object
required: [id, name]
properties:
id:
type: integer
name:
type: string
tag:
type: string
NewPet:
type: object
required: [name]
properties:
name:
type: string
tag:
type: string
Error:
type: object
required: [message]
properties:
message:
type: string

Generating the Endpoints on Every Compile​

An sbt sourceGenerators task is a task that sbt runs before it compiles a project: it writes Scala files, returns them, and sbt compiles them together with the hand-written sources. We add one to build.sbt that reads the spec and runs the generator:

zio-http-example-openapi-codegen/build.sbt
import zio.http.endpoint.openapi.OpenAPI
import zio.http.gen.openapi.EndpointGen
import zio.http.gen.scala.CodeGen
import zio.json.yaml._
import zio.schema.codec.JsonCodec

ThisBuild / scalaVersion := "2.13.18"

name := "zio-http-example-openapi-codegen"

publish / skip := true
publishArtifact := false
run / fork := true

libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"

Compile / sourceGenerators += Def.task {
val spec = (Compile / sourceDirectory).value / "openapi" / "petstore.yaml"
val outputDir = (Compile / sourceManaged).value / "openapi"

val openAPI = IO.read(spec).fromYaml[OpenAPI](JsonCodec.jsonDecoder(OpenAPI.schema)) match {
case Right(api) => api
case Left(error) => sys.error(s"Cannot read $spec: $error")
}

IO.delete(outputDir)
CodeGen
.writeFiles(
EndpointGen.fromOpenAPI(openAPI),
basePath = outputDir.toPath,
basePackage = "example.petstore.api",
scalafmtPath = None,
)
.map(_.toFile)
.toSeq
}.taskValue

The task does three things:

  1. It reads the YAML file into an OpenAPI value. fromYaml comes from zio-json-yaml, and JsonCodec.jsonDecoder(OpenAPI.schema) is the decoder that OpenAPI.fromJson uses for JSON. For a JSON spec, replace the whole match with OpenAPI.fromJson(IO.read(spec)), which returns the same Either[String, OpenAPI].
  2. EndpointGen.fromOpenAPI(openAPI) turns the document into Code.Files, a description of the Scala files to write.
  3. CodeGen.writeFiles writes those files under outputDir. basePackage is the package the generated code goes into. With scalafmtPath = None, the code is written exactly as the generator renders it; pass Some(path) with the path of a .scalafmt.conf file to format it with Scalafmt first.

The task deletes the output directory before it writes, so a file for an operation that was removed from the spec does not stay behind. It writes into sourceManaged, a directory under target/, so the generated code is never checked in. Every sbt compile writes it again from the spec.

What the Generator Produces​

After sbt compile, the generated files are under target/scala-2.13/src_managed/main/openapi/. For the pet store spec, the generator writes these five files:

Pets.scala
package example.petstore.api

import example.petstore.api.component._
import zio.Chunk

object Pets{
import zio.http._
import zio.http.endpoint._
import zio.http.codec._
val listPets=Endpoint(Method.GET / "pets")
.query(HttpCodec.query[Long]("limit"))

.in[Unit]
.out[Chunk[Pet]](status = Status.Ok)



val createPet=Endpoint(Method.POST / "pets")


.in[NewPet]
.out[Pet](status = Status.Created)




}
component/Error.scala
package example.petstore.api.component

import zio.schema._

case class Error(
message: String
)
object Error{
implicit val codec: Schema[Error] = DeriveSchema.gen[Error]
}
component/NewPet.scala
package example.petstore.api.component

import zio.schema._

case class NewPet(
name: String,
tag: Option[String]
)
object NewPet{
implicit val codec: Schema[NewPet] = DeriveSchema.gen[NewPet]
}
component/Pet.scala
package example.petstore.api.component

import zio.schema._

case class Pet(
id: Long,
name: String,
tag: Option[String]
)
object Pet{
implicit val codec: Schema[Pet] = DeriveSchema.gen[Pet]
}
pets/PetId.scala
package example.petstore.api.pets

import example.petstore.api.component._

object PetId{
import zio.http._
import zio.http.endpoint._
import zio.http.codec._
val getPet=Endpoint(Method.GET / "pets" / long("petId"))


.in[Unit]
.out[Pet](status = Status.Ok)
.outError[Error](status = Status.NotFound)



}

The generator maps the spec to Scala like this:

  • Each schema becomes a case class in the component package, with an implicit Schema derived by DeriveSchema.gen. The Schema is what ZIO HTTP uses to encode and decode the JSON bodies. A property that is not in the schema's required list becomes an Option, like tag: Option[String].
  • Each path becomes an object named after the last segment of the path, in a package made of the segments before it. /pets becomes the object Pets in example.petstore.api, and /pets/{petId} becomes the object PetId in example.petstore.api.pets.
  • Each operation becomes an Endpoint value in the object of its path, named after its operationId. An operation without an operationId is named after its HTTP method, such as get or post.
  • Each response becomes an output. Responses with a success status become out calls with their status, so createPet responds with 201 Created. Responses with an error status, 4xx or 5xx, become outError calls, so getPet fails with an Error sent as a 404.
  • An integer without a format becomes a Long, both in the path codec long("petId") and in the fields of Pet.

Every query parameter is generated as required, whatever its required field says in the spec. The spec marks limit as optional, but the generated HttpCodec.query[Long]("limit") needs it: a server built from it responds to GET /pets with 400 Bad Request, and a client built from it always sends limit.

Implementing the Endpoints as a Server​

The generated endpoints are ordinary Endpoint values, so we implement them like any other: Endpoint#implement takes a function from the endpoint's input to a ZIO effect that produces its output, and returns a Route. The server below keeps the pets in a Ref and serves the three generated endpoints:

zio-http-example-openapi-codegen/src/main/scala/example/petstore/PetStoreServer.scala
package example.petstore

import zio._

import zio.http._

import example.petstore.api.Pets
import example.petstore.api.component._
import example.petstore.api.pets.PetId

object PetStoreServer extends ZIOAppDefault {

def routes(pets: Ref[Map[Long, Pet]]): Routes[Any, Response] =
Routes(
Pets.listPets.implement { limit =>
pets.get.map(all => Chunk.fromIterable(all.values).sortBy(_.id).take(limit.toInt))
},
Pets.createPet.implement { newPet =>
pets.modify { all =>
val pet = Pet(all.size + 1L, newPet.name, newPet.tag)
(pet, all + (pet.id -> pet))
}
},
PetId.getPet.implement { petId =>
pets.get.flatMap { all =>
ZIO.fromOption(all.get(petId)).orElseFail(Error(s"No pet has the id $petId"))
}
},
)

val run =
Ref
.make(Map(1L -> Pet(1L, "Rex", Some("dog"))))
.flatMap(pets => Server.serve(routes(pets)))
.provide(Server.default)
}

The types of the three handler functions all come from the generated code:

  • Pets.listPets has the limit query parameter as its only input, so its handler takes a Long and returns the pets as a Chunk[Pet].
  • Pets.createPet has a NewPet request body as its input and a Pet as its output. The 201 Created status comes from the spec.
  • PetId.getPet takes the petId path segment as a Long. Its error type is the generated Error case class, so failing the effect with Error(...) sends a 404 response with that error as its JSON body.

If the handler returned the wrong type, for example a List[Pet] instead of a Chunk[Pet] from listPets, or failed getPet with a String, the code would not compile.

Start the server with sbt "runMain example.petstore.PetStoreServer" and send it requests:

$ curl 'http://localhost:8080/pets?limit=10'
[{"id":1,"name":"Rex","tag":"dog"}]

$ curl -X POST http://localhost:8080/pets -H 'Content-Type: application/json' -d '{"name":"Whiskers","tag":"cat"}'
{"id":2,"name":"Whiskers","tag":"cat"}

$ curl -i http://localhost:8080/pets/42
HTTP/1.1 404 Not Found
content-type: application/json
date: Tue, 01 Dec 2026 19:49:01 GMT
content-length: 34

{"message":"No pet has the id 42"}

The JSON bodies use the field names of the spec, because the generated case classes use them as their field names.

A request without limit fails to decode, because the generated listPets requires the query parameter:

$ curl -i http://localhost:8080/pets
HTTP/1.1 400 Bad Request
content-type: text/html
date: Tue, 01 Dec 2026 19:49:01 GMT
content-length: 190

<html><body><h1>Codec Error</h1><p>There was an error en-/decoding the request/response</p><p id="name">MissingQueryParams</p><p id="message">Missing query parameters limit</p></body></html>

Calling the API with the Generated Endpoints​

The same generated endpoints describe the API for a client. An EndpointExecutor sends endpoint calls to a server through a ZIO HTTP Client. Applying a generated endpoint to its input, as in Pets.listPets(10L), builds an invocation, and the executor sends it and decodes the response:

zio-http-example-openapi-codegen/src/main/scala/example/petstore/PetStoreClient.scala
package example.petstore

import zio._

import zio.http._
import zio.http.endpoint.EndpointExecutor

import example.petstore.api.Pets
import example.petstore.api.component._
import example.petstore.api.pets.PetId

object PetStoreClient extends ZIOAppDefault {

val calls: ZIO[Client & Scope, Throwable, Unit] =
for {
client <- ZIO.service[Client]
executor = EndpointExecutor(client, url"http://localhost:8080")
created <- executor(Pets.createPet(NewPet("Whiskers", Some("cat"))))
_ <- Console.printLine(s"created: $created")
pets <- executor(Pets.listPets(10L))
_ <- Console.printLine(s"pets: $pets")
missing <- executor(PetId.getPet(42L)).either
_ <- Console.printLine(s"pet 42: $missing")
} yield ()

val run = ZIO.scoped(calls).provide(Client.default)
}

executor(PetId.getPet(42L)) fails with the generated Error type when the server responds with a 404, and ZIO#either turns that failure into a Left so the program can print it.

Start a fresh server, then run the client with sbt "runMain example.petstore.PetStoreClient". It prints:

created: Pet(2,Whiskers,Some(cat))
pets: Chunk(Pet(1,Rex,Some(dog)),Pet(2,Whiskers,Some(cat)))
pet 42: Left(Error(No pet has the id 42))

The client does not need a server written with ZIO HTTP. It calls any server that implements the spec, so the same generated code works for calling a third-party API from its published OpenAPI spec.

Adjusting the Generated Code​

EndpointGen.fromOpenAPI takes a second argument, a Config that controls how the generator names and types things. Config.default turns every option off. A common reason to change it is a spec with snake_case property names, which would otherwise become snake_case field names in Scala.

The schema below has the properties full_name and birth_date. With fieldNamesNormalization turned on, the generator names the fields fullName and birthDate and keeps each JSON name in a @fieldName annotation, so the JSON still uses full_name and birth_date:

import zio.http.endpoint.openapi.OpenAPI
import zio.http.gen.openapi.{Config, EndpointGen}
import zio.http.gen.scala.CodeGen
import zio.json.yaml._
import zio.schema.codec.JsonCodec

val ownerSpec =
"""|openapi: 3.0.3
|info:
| title: Owners
| version: 1.0.0
|paths: {}
|components:
| schemas:
| Owner:
| type: object
| required: [full_name, birth_date]
| properties:
| full_name:
| type: string
| birth_date:
| type: string
| format: date
|""".stripMargin

val ownerAPI =
ownerSpec.fromYaml[OpenAPI](JsonCodec.jsonDecoder(OpenAPI.schema)).fold(sys.error(_), identity)

val config =
Config.default.copy(
fieldNamesNormalization = Config.NormalizeFields(enableAutomatic = true, manualOverrides = Map.empty),
)
val ownerFiles = CodeGen.renderedFiles(EndpointGen.fromOpenAPI(ownerAPI, config), "example.owners")

The spec has no paths, so the map has one file, component/Owner.scala. The date format of birth_date becomes a java.time.LocalDate:

component/Owner.scala
package example.owners.component

import zio.schema._
import zio.schema.annotation.fieldName
import java.time.LocalDate

case class Owner(
@fieldName("full_name") fullName: String,
@fieldName("birth_date") birthDate: LocalDate
)
object Owner{
implicit val codec: Schema[Owner] = DeriveSchema.gen[Owner]
}

In the sourceGenerators task, pass the config as the second argument in the same way: EndpointGen.fromOpenAPI(openAPI, config). The other options are listed on the OpenAPI Config reference page.

Running the Example​

All the code from this guide is in the standalone sbt project zio-http-example-openapi-codegen/. From that folder, start the server with sbt "runMain example.petstore.PetStoreServer", and run the client in another terminal with sbt "runMain example.petstore.PetStoreClient". The server listens on port 8080.

Going Further​

  • The OpenAPI Config reference page lists every option of Config.
  • The Endpoint reference covers what you can do with the generated endpoints, such as adding middleware or serving their OpenAPI document with Swagger UI.
  • How to Map Domain Errors to HTTP Responses shows how to turn the errors of your own services into the error types the generated endpoints declare.
  • The Client reference explains how to configure the client that EndpointExecutor uses.