From Routes to Declarative Endpoints, with OpenAPI, Swagger UI and a Typed Client
Welcome! This tutorial is for Scala developers who can already write a small ZIO HTTP server with Routes and handlers, and who now want to describe their API once and get documentation and a client for free. You don't need any prior experience with the Endpoint API, OpenAPI or Swagger UI to follow along. If you have never written a ZIO HTTP route, start with the Build Your First REST API tutorial and come back here afterwards.
Learning Objectives
By the end of this tutorial, you will understand:
- What a declarative endpoint is, and how it differs from a route with a handler
- How to describe path parameters, query parameters, request bodies, responses and typed errors with
Endpoint - How to turn endpoints into a server, an OpenAPI document and a Swagger UI page
- How to call the same endpoints from Scala with a typed client
We'll learn these concepts through:
- The Starting Point: A Plain Routes App
- Describe a Route as an Endpoint
- Add Query Parameters, Bodies and Typed Errors
- Generate the OpenAPI Document
- Serve Swagger UI
- Call the API with a Typed Client
We recommend reading from top to bottom — each section builds on the previous one.
Background
A route with a handler is a function: it receives a Request and returns a Response. ZIO HTTP can run that function, but it cannot look inside it. It cannot tell which query parameters the handler reads, which JSON shape it expects, or which status codes it returns. That knowledge lives only in the handler's code, so the documentation and every client have to be written by hand, and they drift apart from the server over time.
An endpoint turns this around. An Endpoint is a plain value that describes one operation of your API: its method and path, its inputs, its output and its errors. Because the description is data, ZIO HTTP can read it in several ways. The same Endpoint value becomes a server route, an entry in an OpenAPI document, and a call from a typed client:
┌──► Route Endpoint#implement (section 2)
│
Endpoint (description) ─┼──► OpenAPI JSON OpenAPIGen.fromEndpoints (section 4)
│ └──► Swagger UI page (section 5)
│
└──► Invocation EndpointExecutor (section 6)
Setup
All the APIs in this tutorial live in the core ZIO HTTP module, which also brings in ZIO Schema for deriving JSON codecs. Add it to your build.sbt:
libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"
1. The Starting Point: A Plain Routes App
Our running example is a small movie catalog. Before we touch endpoints, let's look at the data and at the API written the way you already know.
The catalog has three data types: a Movie, a NewMovie that a client sends to add a movie, and a MovieNotFound error. Each one gets a Schema, which ZIO HTTP uses to encode and decode JSON. A small in-memory repository stores the movies:
import zio._
import zio.schema.{DeriveSchema, Schema}
final case class Movie(id: Int, title: String, year: Int)
object Movie {
implicit val schema: Schema[Movie] = DeriveSchema.gen[Movie]
}
final case class NewMovie(title: String, year: Int)
object NewMovie {
implicit val schema: Schema[NewMovie] = DeriveSchema.gen[NewMovie]
}
final case class MovieNotFound(id: Int)
object MovieNotFound {
implicit val schema: Schema[MovieNotFound] = DeriveSchema.gen[MovieNotFound]
}
final class MovieRepo(movies: Ref[Map[Int, Movie]]) {
def list(year: Option[Int]): UIO[List[Movie]] =
movies.get.map(_.values.toList.sortBy(_.id).filter(movie => year.forall(_ == movie.year)))
def get(id: Int): IO[MovieNotFound, Movie] =
movies.get.flatMap(all => ZIO.fromOption(all.get(id)).orElseFail(MovieNotFound(id)))
def add(newMovie: NewMovie): UIO[Movie] =
movies.modify { all =>
val movie = Movie(all.size + 1, newMovie.title, newMovie.year)
(movie, all + (movie.id -> movie))
}
}
object MovieRepo {
val layer: ULayer[MovieRepo] =
ZLayer(
Ref
.make(
Map(
1 -> Movie(1, "Spirited Away", 2001),
2 -> Movie(2, "Arrival", 2016),
3 -> Movie(3, "Parasite", 2019),
),
)
.map(new MovieRepo(_)),
)
}
The code above defines:
Movie,NewMovieandMovieNotFound— the shapes that travel over HTTP, each with aSchemaderived byDeriveSchema.gen.MovieRepo#list— returns all movies, or only those from oneyearwhen it isSome.MovieRepo#get— returns one movie, or fails withMovieNotFound. Notice that the error is part of the type:IO[MovieNotFound, Movie].MovieRepo#add— stores a new movie under the next free id and returns it.MovieRepo.layer— aZLayerthat starts the repository with three movies.
Now the API itself, written with plain routes. Each handler reads what it needs from the Request and builds the Response by hand:
import zio.schema.codec.JsonCodec.schemaBasedBinaryCodec
import zio.http._
val plainRoutes: Routes[MovieRepo, Response] =
Routes(
Method.GET / "movies" -> handler { (req: Request) =>
val year = req.query[Int]("year").toOption
ZIO.serviceWithZIO[MovieRepo](_.list(year)).map(movies => Response(body = Body.from(movies)))
},
Method.GET / "movies" / int("id") -> handler { (id: Int, _: Request) =>
ZIO
.serviceWithZIO[MovieRepo](_.get(id))
.mapBoth(
notFound => Response.notFound(s"No movie with id ${notFound.id}"),
movie => Response(body = Body.from(movie)),
)
},
Method.POST / "movies" -> handler { (req: Request) =>
for {
newMovie <- req.body.to[NewMovie].orElseFail(Response.badRequest("Invalid movie"))
movie <- ZIO.serviceWithZIO[MovieRepo](_.add(newMovie))
} yield Response(status = Status.Created, body = Body.from(movie))
},
)
The three routes work like this:
GET /moviesreads the optionalyearquery parameter withRequest#queryand turns the list of movies into a JSON body withBody.from.GET /movies/{id}captures the id with theint("id")path codec, and converts aMovieNotFoundinto a 404 response with a text message.POST /moviesdecodes the request body withBody#to, answers 400 when that fails, and returns the stored movie with status 201.- The
JsonCodec.schemaBasedBinaryCodecimport is what letsBody.fromandBody#touse each type'sSchemafor JSON.
To start the server, we provide the server and the repository layers:
Server.serve(plainRoutes).provide(Server.default, MovieRepo.layer)
Server.default listens on port 8080. Let's try a few requests with curl while the server runs:
curl -i 'localhost:8080/movies?year=2016'
curl -i localhost:8080/movies/42
curl -i -X POST localhost:8080/movies -H 'content-type: application/json' -d '{"title":"Perfect Days","year":2023}'
The server answers each request (date headers removed):
HTTP/1.1 200 OK
content-length: 40
[{"id":2,"title":"Arrival","year":2016}]
HTTP/1.1 404 Not Found
content-length: 19
No movie with id 42
HTTP/1.1 201 Created
content-length: 43
{"id":4,"title":"Perfect Days","year":2023}
The API works, but look at what is missing. Nothing outside the handlers knows that year is an optional integer, that the 404 body is plain text, or that a movie has three fields. Notice also that no response says it contains JSON: there is no content-type header, because we built every body by hand. To document this API, or to call it from another Scala program, we would have to read the handlers and write everything again.
2. Describe a Route as an Endpoint
Let's rewrite the simplest route, GET /movies without the year filter, as an endpoint. We do it in two steps: first we describe the operation, then we implement it.
The description starts from a route pattern and adds the output type:
import zio.http.endpoint._
val listMovies =
Endpoint(Method.GET / "movies").out[List[Movie]]
Endpoint.apply takes the same kind of route pattern as a plain route, Method.GET / "movies". Endpoint#out declares that a successful call returns a List[Movie], encoded with the Schema we derived in section 1. The endpoint has no handler yet; it is only a description, so we can pass it around and inspect it like any other value.
To serve it, we implement the endpoint with a function from its input to a ZIO effect that produces its output:
val listMoviesRoute =
listMovies.implement(_ => ZIO.serviceWithZIO[MovieRepo](_.list(None)))
Endpoint#implement returns a Route, the same type that Method.GET / "movies" -> handler { ... } creates. This endpoint has no inputs, so the function receives () and ignores it. The function never touches a Request or a Response: it receives decoded inputs and returns a plain List[Movie], and the endpoint takes care of HTTP.
A Route goes into Routes and is served exactly like before:
Server.serve(Routes(listMoviesRoute)).provide(Server.default, MovieRepo.layer)
Let's call it with curl -i localhost:8080/movies:
HTTP/1.1 200 OK
content-type: application/json
content-length: 125
[{"id":1,"title":"Spirited Away","year":2001},{"id":2,"title":"Arrival","year":2016},{"id":3,"title":"Parasite","year":2019}]
The body is the same as before, and this time the response carries content-type: application/json. We never wrote that header: the endpoint knows its output is JSON because we told it so with Endpoint#out.
3. Add Query Parameters, Bodies and Typed Errors
Now let's describe the whole movie API. Each part of a request or response that a handler reads or builds by hand in section 1 becomes one method call on the endpoint. We also attach a short description to each part with the ?? operator and a Doc; we will see those descriptions again in section 4.
We keep the three endpoints together in one object, so the server and, later, the client can share them:
import zio.http.codec._
object MovieEndpoints {
val listMovies =
Endpoint(Method.GET / "movies")
.query(HttpCodec.query[Int]("year").optional ?? Doc.p("Only movies released in this year."))
.out[List[Movie]](Doc.p("The movies, ordered by id.")) ?? Doc.p("Lists the movies in the catalog.")
val getMovie =
Endpoint(Method.GET / "movies" / int("id"))
.out[Movie](Doc.p("The movie with this id."))
.outError[MovieNotFound](Status.NotFound, Doc.p("No movie has this id.")) ?? Doc.p("Returns one movie.")
val createMovie =
Endpoint(Method.POST / "movies")
.in[NewMovie](Doc.p("The title and release year of the new movie."))
.out[Movie](Status.Created, Doc.p("The stored movie, with its new id.")) ?? Doc.p("Adds a movie to the catalog.")
}
Each endpoint adds one new idea:
Endpoint#queryadds a query parameter to the input.HttpCodec.query[Int]("year")readsyearas anInt, andHttpCodec#optionalmakes it anOption[Int]that isNonewhen the parameter is missing.int("id")in the route pattern is a path parameter, so the input ofMovieEndpoints.getMovieis anInt.Endpoint#outErrordeclares a typed error: when the implementation fails with aMovieNotFound, the client gets status 404 with the error as a JSON body.Endpoint#indeclares the request body, decoded from JSON into aNewMovie.Endpoint#outwith aStatussets the success status;MovieEndpoints.createMovieanswers 201 Created instead of 200.??attaches aDocto the part on its left: to the query parameter, or to the whole endpoint when it ends the chain.Doc.pcreates one paragraph of text.
The types follow the description. MovieEndpoints.getMovie has input Int, error MovieNotFound and output Movie, so Endpoint#implement only accepts a function of type Int => ZIO[R, MovieNotFound, Movie]. That is exactly the shape of MovieRepo#get:
val movieRoutes: Routes[MovieRepo, Nothing] =
Routes(
MovieEndpoints.listMovies.implement(year => ZIO.serviceWithZIO[MovieRepo](_.list(year))),
MovieEndpoints.getMovie.implement(id => ZIO.serviceWithZIO[MovieRepo](_.get(id))),
MovieEndpoints.createMovie.implement(newMovie => ZIO.serviceWithZIO[MovieRepo](_.add(newMovie))),
)
Compare these three lines with the handlers of section 1. There is no request parsing, no Body.from, no mapBoth that turns an error into a response. Each implementation is the repository call and nothing else. The error type of movieRoutes is Nothing because every failure is already described by an endpoint and turned into a response for us.
Let's serve it the same way:
Server.serve(movieRoutes).provide(Server.default, MovieRepo.layer)
The same three curl requests as in section 1 now answer:
HTTP/1.1 200 OK
content-type: application/json
content-length: 40
[{"id":2,"title":"Arrival","year":2016}]
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 9
{"id":42}
HTTP/1.1 201 Created
content-type: application/json
content-length: 43
{"id":4,"title":"Perfect Days","year":2023}
Notice the 404: its body is now the MovieNotFound value as JSON, so a client can decode it just like a successful response.
4. Generate the OpenAPI Document
OpenAPI is a standard JSON format for describing HTTP APIs. Tools read it to render documentation, generate clients in other languages, or test an API. Because our endpoints are descriptions, ZIO HTTP can write this document for us.
OpenAPIGen.fromEndpoints takes a title, a version and the endpoints to include:
import zio.http.endpoint.openapi._
val openAPI =
OpenAPIGen.fromEndpoints(
title = "Movie API",
version = "1.0",
MovieEndpoints.listMovies,
MovieEndpoints.getMovie,
MovieEndpoints.createMovie,
)
The result is an OpenAPI value. Let's print it as JSON with OpenAPI#toJsonPretty:
println(openAPI.toJsonPretty)
// {
// "openapi" : "3.1.0",
// "info" : {
// "title" : "Movie API",
// "version" : "1.0"
// },
// "paths" : {
// "/movies" : {
// "description" : "Lists the movies in the catalog.\n\nAdds a movie to the catalog.\n\n",
// "get" : {
// "description" : "Lists the movies in the catalog.\n\n",
// "parameters" : [
// {
// "name" : "year",
// "in" : "query",
// "description" : "Only movies released in this year.\n\n",
// "schema" : {
// "type" : "integer",
// "format" : "int32"
// },
// "allowReserved" : false,
// "style" : "form"
// }
// ],
// "responses" : {
// "200" : {
// "description" : "The movies, ordered by id.\n\n",
// "content" : {
// "application/json" : {
// "schema" : {
// "type" : "array",
// "items" : {
// "$ref" : "#/components/schemas/Movie"
// }
// }
// }
// }
// }
// }
// },
// "post" : {
// "description" : "Adds a movie to the catalog.\n\n",
// "requestBody" : {
// "content" : {
// "application/json" : {
// "schema" : {
// "$ref" : "#/components/schemas/NewMovie",
// "description" : "The title and release year of the new movie.\n\n"
// }
// }
// },
// "required" : true
// },
// "responses" : {
// "201" : {
// "description" : "The stored movie, with its new id.\n\n",
// "content" : {
// "application/json" : {
// "schema" : {
// "$ref" : "#/components/schemas/Movie"
// }
// }
// }
// }
// }
// }
// },
// "/movies/{id}" : {
// "description" : "Returns one movie.\n\n",
// "get" : {
// "description" : "Returns one movie.\n\n",
// "parameters" : [
// {
// "name" : "id",
// "in" : "path",
// "required" : true,
// "schema" : {
// "type" : "integer",
// "format" : "int32"
// },
// "style" : "simple"
// }
// ],
// "responses" : {
// "200" : {
// "description" : "The movie with this id.\n\n",
// "content" : {
// "application/json" : {
// "schema" : {
// "$ref" : "#/components/schemas/Movie"
// }
// }
// }
// },
// "404" : {
// "description" : "No movie has this id.\n\n",
// "content" : {
// "application/json" : {
// "schema" : {
// "$ref" : "#/components/schemas/MovieNotFound"
// }
// }
// }
// }
// }
// }
// }
// },
// "components" : {
// "schemas" : {
// "Movie" : {
// "type" : "object",
// "properties" : {
// "id" : {
// "type" : "integer",
// "format" : "int32"
// },
// "title" : {
// "type" : "string"
// },
// "year" : {
// "type" : "integer",
// "format" : "int32"
// }
// },
// "required" : [
// "id",
// "title",
// "year"
// ]
// },
// "MovieNotFound" : {
// "type" : "object",
// "properties" : {
// "id" : {
// "type" : "integer",
// "format" : "int32"
// }
// },
// "required" : [
// "id"
// ]
// },
// "NewMovie" : {
// "type" : "object",
// "properties" : {
// "title" : {
// "type" : "string"
// },
// "year" : {
// "type" : "integer",
// "format" : "int32"
// }
// },
// "required" : [
// "title",
// "year"
// ]
// }
// }
// }
// }
Take a moment to find each piece of our endpoints in the output:
- Under
paths,/movieshas agetand apostoperation, and/movies/{id}has aget, with the descriptions we wrote after??. - The
yearquery parameter has no"required": true, so tools know they can leave it out; theidpath parameter is required. - Each operation lists its responses by status code: 200 and 404 for
MovieEndpoints.getMovie, 201 forMovieEndpoints.createMovie, each with its description and a reference to a schema. - Under
components, the schemas ofMovie,NewMovieandMovieNotFoundcome from theSchemavalues we derived in section 1.
We wrote none of this JSON by hand, and we cannot forget to update it: when an endpoint changes, the next call to OpenAPIGen.fromEndpoints describes the new version.
Give every Endpoint#out and Endpoint#outError a Doc, as we did above. OpenAPI 3.1 requires a description for every response, and that Doc becomes the description.
5. Serve Swagger UI
Swagger UI is a web page that renders an OpenAPI document as interactive documentation: it lists the operations, shows the schemas, and has a "Try it out" button that sends real requests. ZIO HTTP can serve it next to our API.
SwaggerUI.routes takes the path to serve the page at and one or more OpenAPI documents, and returns ordinary Routes:
import zio.http.codec.PathCodec._
val swaggerRoutes: Routes[Any, Response] =
SwaggerUI.routes("docs" / "openapi", openAPI)
val app: Routes[MovieRepo, Response] =
movieRoutes ++ swaggerRoutes
The new routes serve two things:
GET /docs/openapireturns the Swagger UI page.GET /docs/openapi/Movie+API.jsonreturns our OpenAPI document. The last segment is the document's title, URL-encoded, plus a JSON file extension.++combines the API routes and the documentation routes into oneRoutesvalue,app.
We serve app instead of movieRoutes:
Server.serve(app).provide(Server.default, MovieRepo.layer)
Now open http://localhost:8080/docs/openapi in a browser. You see the "Movie API" with its three operations. Expand GET /movies/{id}, click "Try it out", enter 42 and execute it: Swagger UI shows the 404 response with the body {"id":42}. Try POST /movies too; Swagger UI fills the request body with the shape of NewMovie for you.
The Swagger UI page loads its scripts and styles from the unpkg.com CDN, so the browser needs internet access to render it. The OpenAPI JSON itself comes from your server.
Runnable version, with the implemented endpoints of section 3 and the document of section 4: Concept5SwaggerUIExample.scala
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-schema-derivation:1.9.2"
//> using file Model.scala
//> using file MovieEndpoints.scala
// Run from this folder: scala-cli run Concept5SwaggerUIExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.endpoint.fromroutes.Concept5SwaggerUIExample"
package example.endpoint.fromroutes
import zio._
import zio.http._
import zio.http.codec.PathCodec._
import zio.http.endpoint.openapi._
/**
* From Routes to Declarative Endpoints — 5. Serve Swagger UI
*
* Serves the movie API together with its OpenAPI document and Swagger UI.
*/
object Concept5SwaggerUIExample extends ZIOAppDefault {
// Setup from section 3: the implemented endpoints
val movieRoutes: Routes[MovieRepo, Nothing] =
Routes(
MovieEndpoints.listMovies.implement(year => ZIO.serviceWithZIO[MovieRepo](_.list(year))),
MovieEndpoints.getMovie.implement(id => ZIO.serviceWithZIO[MovieRepo](_.get(id))),
MovieEndpoints.createMovie.implement(newMovie => ZIO.serviceWithZIO[MovieRepo](_.add(newMovie))),
)
// Setup from section 4: the OpenAPI document
val openAPI =
OpenAPIGen.fromEndpoints(
title = "Movie API",
version = "1.0",
MovieEndpoints.listMovies,
MovieEndpoints.getMovie,
MovieEndpoints.createMovie,
)
val swaggerRoutes: Routes[Any, Response] =
SwaggerUI.routes("docs" / "openapi", openAPI)
val app: Routes[MovieRepo, Response] =
movieRoutes ++ swaggerRoutes
def run = Server.serve(app).provide(Server.default, MovieRepo.layer)
}
6. Call the API with a Typed Client
So far the endpoints have served requests and described the API. Their third use is on the other side of the wire: calling the API from Scala, with the same types the server uses.
An EndpointExecutor sends endpoint calls to a server through a ZIO HTTP Client. We build one from a client and the server's base URL, then call endpoints like functions:
val clientCalls: ZIO[Client & Scope, Nothing, Unit] =
for {
client <- ZIO.service[Client]
executor = EndpointExecutor(client, url"http://localhost:8080")
created <- executor(MovieEndpoints.createMovie(NewMovie("Perfect Days", 2023)))
_ <- Console.printLine(s"created: $created").orDie
movies <- executor(MovieEndpoints.listMovies(Some(2023)))
_ <- Console.printLine(s"movies from 2023: $movies").orDie
missing <- executor(MovieEndpoints.getMovie(42)).either
_ <- Console.printLine(s"movie 42: $missing").orDie
} yield ()
Let's walk through it:
EndpointExecutor(client, url"http://localhost:8080")creates an executor that sends every call to that base URL. Theurlinterpolator checks the URL when the code compiles.MovieEndpoints.createMovie(NewMovie("Perfect Days", 2023))does not send anything yet. Applying an endpoint to its input returns anInvocation: a value that pairs the endpoint with the input to send.executor(...)runs the invocation: it encodes the input as the endpoint describes, sends the request, and decodes the response into aMovie.MovieEndpoints.listMovies(Some(2023))fills the optionalyearquery parameter. PassingNonewould leave it out.executor(MovieEndpoints.getMovie(42))has the typeZIO[Scope, MovieNotFound, Movie]. The server's 404 comes back as aMovieNotFoundin the error channel, andZIO#eitherturns it into aLeftso we can print it.
The compiler checks every call against the endpoint: passing a String as the movie id, or expecting a List[Movie] from MovieEndpoints.getMovie, does not compile.
To run the calls, we provide a Client and a Scope, in which the client's requests run:
ZIO.scoped(clientCalls).provide(Client.default)
Start the server from section 5 in one terminal and run the client in another. It prints:
created: Movie(4,Perfect Days,2023)
movies from 2023: List(Movie(4,Perfect Days,2023))
movie 42: Left(MovieNotFound(42))
This is the moment to step back: MovieEndpoints.getMovie is a single value. The server implements it, the OpenAPI document describes it, Swagger UI renders it, and the client calls it. If we change its path or its output type, all four change together, and the compiler points at every implementation and call that no longer fits.
Putting It Together
The complete example combines everything in one program. It differs from the sections in these ways: the server and the client run in the same program, so one provide supplies Server.default, MovieRepo.layer and Client.default together. The server starts with Server.install instead of Server.serve, and Server.install returns the port as soon as the routes are installed, so the program prints the Swagger UI address, runs the client calls of section 6 with ZIO.scoped against its own server, and then waits with ZIO.never so you can keep exploring Swagger UI until you press Ctrl+C. It also writes the Swagger UI routes inline in app instead of in a separate swaggerRoutes value, and it does not print the OpenAPI document of section 4:
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-schema-derivation:1.9.2"
//> using file Model.scala
//> using file MovieEndpoints.scala
// Run from this folder: scala-cli run CompleteExample.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.endpoint.fromroutes.CompleteExample"
package example.endpoint.fromroutes
import zio._
import zio.http._
import zio.http.codec.PathCodec._
import zio.http.endpoint._
import zio.http.endpoint.openapi._
/**
* From Routes to Declarative Endpoints — Putting It Together
*
* One program: the server implements the movie endpoints and serves their
* OpenAPI document and Swagger UI, then a typed client built from the same
* endpoints calls it. The server keeps running until Ctrl+C.
*/
object CompleteExample extends ZIOAppDefault {
val movieRoutes: Routes[MovieRepo, Nothing] =
Routes(
MovieEndpoints.listMovies.implement(year => ZIO.serviceWithZIO[MovieRepo](_.list(year))),
MovieEndpoints.getMovie.implement(id => ZIO.serviceWithZIO[MovieRepo](_.get(id))),
MovieEndpoints.createMovie.implement(newMovie => ZIO.serviceWithZIO[MovieRepo](_.add(newMovie))),
)
val openAPI =
OpenAPIGen.fromEndpoints(
title = "Movie API",
version = "1.0",
MovieEndpoints.listMovies,
MovieEndpoints.getMovie,
MovieEndpoints.createMovie,
)
val app: Routes[MovieRepo, Response] =
movieRoutes ++ SwaggerUI.routes("docs" / "openapi", openAPI)
val clientCalls: ZIO[Client & Scope, Nothing, Unit] =
for {
client <- ZIO.service[Client]
executor = EndpointExecutor(client, url"http://localhost:8080")
created <- executor(MovieEndpoints.createMovie(NewMovie("Perfect Days", 2023)))
_ <- Console.printLine(s"created: $created").orDie
movies <- executor(MovieEndpoints.listMovies(Some(2023)))
_ <- Console.printLine(s"movies from 2023: $movies").orDie
missing <- executor(MovieEndpoints.getMovie(42)).either
_ <- Console.printLine(s"movie 42: $missing").orDie
} yield ()
val program: ZIO[MovieRepo & Server & Client, Nothing, Unit] =
for {
port <- Server.install(app)
_ <- Console.printLine(s"Swagger UI: http://localhost:$port/docs/openapi").orDie
_ <- ZIO.scoped(clientCalls)
} yield ()
def run = (program *> ZIO.never).provide(Server.default, MovieRepo.layer, Client.default)
}
It prints the Swagger UI address and then the results of the client calls:
Swagger UI: http://localhost:8080/docs/openapi
created: Movie(4,Perfect Days,2023)
movies from 2023: List(Movie(4,Perfect Days,2023))
movie 42: Left(MovieNotFound(42))
Running the Examples
All runnable code from this tutorial is in zio-http-example/src/main/scala/example/endpoint/fromroutes/, one file per section plus the shared Model.scala and MovieEndpoints.scala. Run any file from that folder with scala-cli run <File>.scala, or from the repository root with sbt "zioHttpExample/runMain example.endpoint.fromroutes.<ObjectName>".
What You've Learned
In this tutorial, you learned:
- What a declarative endpoint is: a value that describes an operation, which ZIO HTTP can read, unlike a handler, which it can only run
- How to describe path parameters, optional query parameters, request bodies, success statuses and typed errors with
Endpoint, and how to document each part with?? - How to turn the same endpoints into server routes with
Endpoint#implement, into an OpenAPI document withOpenAPIGen.fromEndpoints, and into a Swagger UI page withSwaggerUI.routes - How to call the endpoints from Scala with an
EndpointExecutor, with typed errors in the error channel
You now have a solid foundation in the Endpoint API. The next step is to apply it to your own API and to explore the codecs that describe inputs and outputs in more detail.
Where to Go Next
- Want the big picture of the API styles? Read the Endpoint concept page, which compares declarative endpoints with routes and handlers.
- Want to dive deeper into the API? The
Endpointreference covers authentication, multiple error types, streaming and more, and theHttpCodecreference explains the codecs behindEndpoint#query,Endpoint#inandEndpoint#out. - Want more control over the client? The
Clientreference explains how to configure the client thatEndpointExecutoruses. - Ready to test your endpoints? The Testing HTTP Applications guide shows how to test routes, including the ones
Endpoint#implementreturns.