How to Build a Command-Line Client from Your Endpoints
In this guide, we turn the endpoint definitions of a small to-do API into a command-line client with the zio-http-cli module. By the end, you will have a todo program with one command per endpoint, typed options for the path parameters, query parameters and headers, a generated help page, and requests that reach a running ZIO HTTP server.
We start from three endpoints and a server that implements them, generate the app with HttpCliApp.fromEndpoints, read its help output, and call the server with it. The last two sections show how the commands are named and what to do when two endpoints end up with the same name.
The Problem
An HTTP API is easy to call from code and awkward to call by hand. With curl, you have to remember every path, query parameter and header name, and nothing tells you that the ID in /todos/{id} must be a number until the server answers with an error. A small command-line tool fixes that, but writing one means a second copy of the API: argument parsing, a usage message, and the request for each command.
For example, a hand-written client for two of the to-do endpoints looks like this:
import zio._
import zio.http._
object HandWrittenTodoCli extends ZIOAppDefault {
val usage = "usage: todo get <id> | todo delete <id> <api-key>"
def send(request: Request): Task[Unit] =
(for {
response <- Client.batched(request)
body <- response.body.asString
_ <- Console.printLine(s"${response.status.code} $body")
} yield ()).provide(Client.default)
val run =
getArgs.flatMap {
case Chunk("get", id) if id.toIntOption.isDefined =>
send(Request.get(s"http://localhost:8080/todos/$id"))
case Chunk("delete", id, apiKey) if id.toIntOption.isDefined =>
send(Request.delete(s"http://localhost:8080/todos/$id").addHeader("x-api-key", apiKey))
case _ =>
Console.printLine(usage)
}
}
Every path, header name and argument check here repeats something the server's endpoint definitions already say. When an endpoint gains a query parameter or changes its path, the client has to be changed by hand, and the usage line has to be kept in step with both.
The zio-http-cli module reads the endpoint definitions instead: HttpCliApp.fromEndpoints builds the commands, their options, the help page and the requests from the same Endpoint values the server implements.
Prerequisites
Add ZIO HTTP and the command-line module to your build.sbt:
// ZIO HTTP server, client and Endpoint API
libraryDependencies += "dev.zio" %% "zio-http" % "3.12.0"
// Command-line clients generated from endpoints (brings in ZIO CLI)
libraryDependencies += "dev.zio" %% "zio-http-cli" % "3.12.0"
This guide assumes you can define endpoints with the Endpoint API and implement them on a server; the declarative endpoints guide walks through both. The generated app is a ZIO CLI application, but you do not need to know ZIO CLI to follow along.
The endpoints in this guide take their input from the path, the query string and headers. A command for an endpoint with a request body sends that body as a multipart/form-data request.
The Endpoints to Expose
The to-do API has three endpoints. TodoEndpoints.getTodo returns one item or a 404 Not Found with a message, TodoEndpoints.deleteTodo needs an x-api-key header and answers 403 Forbidden for a wrong key, and TodoEndpoints.listTodos filters the items by a done query parameter. The text after ?? on each endpoint is its documentation, which the help page shows next to the command:
import zio.schema._
import zio.http._
import zio.http.codec._
import zio.http.endpoint._
final case class Todo(id: Int, title: String, done: Boolean)
object Todo {
implicit val schema: Schema[Todo] = DeriveSchema.gen[Todo]
}
object TodoEndpoints {
val getTodo =
Endpoint(Method.GET / "todos" / int("id"))
.out[Todo]
.outError[String](Status.NotFound) ?? Doc.p("Get a to-do item by its ID")
val deleteTodo =
Endpoint(Method.DELETE / "todos" / int("id"))
.header(HttpCodec.headerAs[String]("x-api-key"))
.out[String]
.outError[String](Status.Forbidden) ?? Doc.p("Delete a to-do item")
val listTodos =
Endpoint(Method.GET / "todos")
.query(HttpCodec.query[Boolean]("done"))
.out[List[Todo]] ?? Doc.p("List to-do items")
}
The server implements the three endpoints over an in-memory map that starts with two items, and accepts the API key let-me-in:
import zio._
object TodoServer extends ZIOAppDefault {
val apiKey = "let-me-in"
def routes(store: Ref[Map[Int, Todo]]): Routes[Any, Response] =
Routes(
TodoEndpoints.getTodo.implement { id =>
store.get.flatMap(todos => ZIO.fromOption(todos.get(id)).orElseFail(s"No to-do item with ID $id"))
},
TodoEndpoints.deleteTodo.implement { case (id, key) =>
if (key != apiKey) ZIO.fail("Wrong API key")
else store.update(_ - id).as(s"Deleted to-do item $id")
},
TodoEndpoints.listTodos.implement { done =>
store.get.map(_.values.filter(_.done == done).toList.sortBy(_.id))
},
)
val run =
Ref
.make(Map(1 -> Todo(1, "Write the guide", done = false), 2 -> Todo(2, "Run the examples", done = true)))
.flatMap(store => Server.serve(routes(store)).provide(Server.default))
}
Server.default listens on port 8080, which is where the command-line app sends its requests.
Generating the Command-Line App
HttpCliApp.fromEndpoints takes the app's name, version and one-line summary, the endpoints to turn into commands, and the host and port of the server. Its cliApp field is a ZIO CLI CliApp, and extending ZIOCliDefault turns it into a program that reads its arguments from the command line. We start with the TodoEndpoints.getTodo and TodoEndpoints.deleteTodo endpoints:
import zio._
import zio.cli._
import zio.http.endpoint.cli._
object TodoCli extends ZIOCliDefault {
val cliApp =
HttpCliApp
.fromEndpoints(
name = "todo",
version = "1.0.0",
summary = HelpDoc.Span.text("Read and delete to-do items"),
endpoints = Chunk(TodoEndpoints.getTodo, TodoEndpoints.deleteTodo),
host = "localhost",
port = 8080,
)
.cliApp
}
The host and port are fixed when the app is built: every command sends its request to http://localhost:8080.
To try the app from sbt, put its arguments after the main class name, inside the quotes:
sbt "runMain TodoCli --help"
The rest of this guide writes a call as todo <arguments>, the name the app gives itself in its usage line.
Reading the Generated Help
Running the app with --help, or with no arguments at all, prints a banner with the app's name, the name, version and summary, and one line per command:
__ __
/ /_____ ____/ /___
/ __/ __ \/ __ / __ \
/ /_/ /_/ / /_/ / /_/ /
\__/\____/\__,_/\____/
todo 1.0.0 -- Read and delete to-do items
USAGE
$ todo <command>
COMMANDS
- get-todos --id <integer> Get a to-do item by its ID
- delete-todos --id <integer> --x-api-key <text> Delete a to-do item
Each command line comes from one endpoint:
- The name is the method, then the literal path segments, joined with
-:GET /todos/{id}becomesget-todos.POSTbecomescreateandPUTbecomesupdate. - The path parameter
int("id")becomes the option--id <integer>, so ZIO CLI rejects a value that is not a number before any request is sent. - The header
x-api-keybecomes the option--x-api-key <text>. - The text on the right is the endpoint's documentation.
A query parameter becomes an option too. For the Boolean done parameter of TodoEndpoints.listTodos, it is the flag [--done]: the brackets mark it as optional, and leaving it out sends done=false.
Read the options of every command from the top-level help. --help after a command name prints the help of the first command in the list.
Calling the Server
With TodoServer running, we call each command. A successful call prints Got response, the status, and the response body:
$ todo get-todos --id 1
Got response
Status: Ok
Body: {"id":1,"title":"Write the guide","done":false}
An error response from the server is printed the same way, with its status and the error body from the endpoint's outError:
$ todo get-todos --id 42
Got response
Status: NotFound
Body: "No to-do item with ID 42"
The header option goes into the request as the x-api-key header, so a wrong key gets the server's 403, and the right one deletes the item:
$ todo delete-todos --id 2 --x-api-key wrong
Got response
Status: Forbidden
Body: "Wrong API key"
$ todo delete-todos --id 2 --x-api-key let-me-in
Got response
Status: Ok
Body: "Deleted to-do item 2"
The app exits with code 0 whenever the server answers, whatever the status, so a script that calls it has to read the Status: line to tell success from an error response. It exits with code 1 when ZIO CLI rejects the arguments, before any request is sent:
$ todo get-todos --id two
two is not a integer.
$ todo get-todos
Expected to find --id option.
It also exits with code 1 when no server answers; the app then logs the failure (zio-cli app failed) with the connection error, for example Connection refused: localhost/127.0.0.1:8080.
Runnable version, with the endpoints from TodoEndpoints.scala: Step4GenerateCliExample.scala and TodoServer.scala
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
package example.cliclient
import zio.schema._
import zio.http._
import zio.http.codec._
import zio.http.endpoint._
/**
* Build a Command-Line Client from Your Endpoints — The Endpoints to Expose
*
* The to-do item model and the three endpoints that the server implements and
* the command-line apps call.
*/
final case class Todo(id: Int, title: String, done: Boolean)
object Todo {
implicit val schema: Schema[Todo] = DeriveSchema.gen[Todo]
}
object TodoEndpoints {
val getTodo =
Endpoint(Method.GET / "todos" / int("id"))
.out[Todo]
.outError[String](Status.NotFound) ?? Doc.p("Get a to-do item by its ID")
val deleteTodo =
Endpoint(Method.DELETE / "todos" / int("id"))
.header(HttpCodec.headerAs[String]("x-api-key"))
.out[String]
.outError[String](Status.Forbidden) ?? Doc.p("Delete a to-do item")
val listTodos =
Endpoint(Method.GET / "todos")
.query(HttpCodec.query[Boolean]("done"))
.out[List[Todo]] ?? Doc.p("List to-do items")
}
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using file TodoEndpoints.scala
// Run from this folder: scala-cli run TodoServer.scala
// Or from the repository root: sbt "zioHttpExample/runMain example.cliclient.TodoServer"
package example.cliclient
import zio._
import zio.http._
/**
* Build a Command-Line Client from Your Endpoints — The Endpoints to Expose
*
* Serves the to-do endpoints on port 8080 from an in-memory map that starts
* with two items.
*/
object TodoServer extends ZIOAppDefault {
val apiKey = "let-me-in"
def routes(store: Ref[Map[Int, Todo]]): Routes[Any, Response] =
Routes(
TodoEndpoints.getTodo.implement { id =>
store.get.flatMap(todos => ZIO.fromOption(todos.get(id)).orElseFail(s"No to-do item with ID $id"))
},
TodoEndpoints.deleteTodo.implement { case (id, key) =>
if (key != apiKey) ZIO.fail("Wrong API key")
else store.update(_ - id).as(s"Deleted to-do item $id")
},
TodoEndpoints.listTodos.implement { done =>
store.get.map(_.values.filter(_.done == done).toList.sortBy(_.id))
},
)
val run =
Ref
.make(Map(1 -> Todo(1, "Write the guide", done = false), 2 -> Todo(2, "Run the examples", done = true)))
.flatMap(store => Server.serve(routes(store)).provide(Server.default))
}
//> using scala 2.13.18
//> using dep "dev.zio::zio-http:3.12.0"
//> using dep "dev.zio::zio-http-cli:3.12.0"
//> using file TodoEndpoints.scala
// Run from this folder: scala-cli run Step4GenerateCliExample.scala -- get-todos --id 1
// Or from the repository root: sbt "zioHttpExample/runMain example.cliclient.Step4GenerateCliExample get-todos --id 1"
package example.cliclient
import zio._
import zio.cli._
import zio.http.endpoint.cli._
/**
* Build a Command-Line Client from Your Endpoints — Generating the Command-Line
* App
*
* A command-line app with one command per endpoint, sending its requests to the
* to-do server on localhost:8080.
*/
object Step4GenerateCliExample extends ZIOCliDefault {
val cliApp =
HttpCliApp
.fromEndpoints(
name = "todo",
version = "1.0.0",
summary = HelpDoc.Span.text("Read and delete to-do items"),
endpoints = Chunk(TodoEndpoints.getTodo, TodoEndpoints.deleteTodo),
host = "localhost",
port = 8080,
)
.cliApp
}
When Two Endpoints Get the Same Name
The command name keeps only the method and the literal path segments, so path parameters and query parameters do not change it. Adding TodoEndpoints.listTodos (GET /todos?done=...) next to TodoEndpoints.getTodo (GET /todos/{id}) therefore gives two commands named get-todos:
import zio._
import zio.cli._
import zio.http.endpoint.cli._
object TodoCliWithList extends ZIOCliDefault {
val cliApp =
HttpCliApp
.fromEndpoints(
name = "todo",
version = "1.0.0",
summary = HelpDoc.Span.text("Read and delete to-do items"),
endpoints = Chunk(TodoEndpoints.getTodo, TodoEndpoints.deleteTodo, TodoEndpoints.listTodos),
host = "localhost",
port = 8080,
)
.cliApp
}
The help lists both commands:
COMMANDS
- get-todos --id <integer> Get a to-do item by its ID
- delete-todos --id <integer> --x-api-key <text> Delete a to-do item
- get-todos [--done] List to-do items
Only the first get-todos in the endpoint list can be called. The arguments of the second one are parsed as the first command's, which needs --id:
$ todo get-todos --done
Expected to find --id option.
A list endpoint and a get-by-ID endpoint on the same path is a common shape for a REST API, so check the generated help for repeated names whenever you add an endpoint.
Using HTTP-Style Command Names
The cliStyle parameter of HttpCliApp.fromEndpoints selects how commands are named. The default, true, gives the names in the sections above. With cliStyle = false, a command is named like an HTTP request line: the same method word, a space, and the path, with the names of the query parameters after a ?. That keeps TodoEndpoints.listTodos apart from TodoEndpoints.getTodo:
import zio._
import zio.cli._
import zio.http.endpoint.cli._
object TodoCliHttpStyle extends ZIOCliDefault {
val cliApp =
HttpCliApp
.fromEndpoints(
name = "todo",
version = "1.0.0",
summary = HelpDoc.Span.text("Read and delete to-do items"),
endpoints = Chunk(TodoEndpoints.getTodo, TodoEndpoints.deleteTodo, TodoEndpoints.listTodos),
host = "localhost",
port = 8080,
cliStyle = false,
)
.cliApp
}
The help now has three different names:
COMMANDS
- get /todos --id <integer> Get a to-do item by its ID
- delete /todos --id <integer> --x-api-key <text> Delete a to-do item
- get /todos?done [--done] List to-do items
Each name contains a space, so it is one argument and needs quotes in the shell. Without --done, the list command returns the items that are not done:
$ todo "get /todos?done"
Got response
Status: Ok
Body: [{"id":1,"title":"Write the guide","done":false}]
The path in these names also leaves out path parameters, so two endpoints that differ only in a path parameter still share a name in this style.
Running the Examples
All runnable code from this guide is in zio-http-example/src/main/scala/example/cliclient/. Start the server from that folder with scala-cli run TodoServer.scala, or from the repository root with sbt "zioHttpExample/runMain example.cliclient.TodoServer". Then run a command-line example with its arguments after --, for example scala-cli run Step4GenerateCliExample.scala -- get-todos --id 1, or from the repository root with sbt "zioHttpExample/runMain example.cliclient.Step4GenerateCliExample get-todos --id 1". Step7SameCommandNameExample.scala and Step8HttpStyleNamesExample.scala hold the apps from the last two sections.
Going Further
- The Endpoint reference shows
HttpCliApp.fromEndpointswith a help footer, and its full source example. - The same endpoint definitions can also produce an OpenAPI document and a typed Scala client; see the Endpoint reference.
- To hand the app to other people as a real
todocommand, package it like any other Scala program, for example with sbt-native-packager, which the packaging guide uses for a server.