How to Generate Endpoints from Protobuf Files
In this guide, we generate ZIO HTTP endpoints from a service described in a .proto file. By the end, an sbt build turns the .proto file into an Endpoint for every method of the service, a server implements those endpoints, and a client calls them with the same generated values.
We add the sbt-zio-http-grpc protoc plugin to an sbt build, describe a small inventory service in a .proto file, look at the code the plugin generates, and then serve and call the endpoints. The last two sections list what the generated endpoints send and accept, and which .proto layouts the plugin supports.
The Problem
When a team describes its API in Protocol Buffers, the .proto file is the source of truth for the messages and the methods. A ZIO HTTP service that implements that API needs a Scala type for every message and an Endpoint for every method, and nothing keeps them in step with the .proto file.
For example, without code generation, the inventory service of this guide looks like this in Scala:
import zio.http._
import zio.http.endpoint._
import zio.schema._
// Hand-written copies of the messages in inventory.proto
case class StockRequest(sku: String)
object StockRequest {
implicit val schema: Schema[StockRequest] = DeriveSchema.gen[StockRequest]
}
case class RestockRequest(sku: String, quantity: Int)
object RestockRequest {
implicit val schema: Schema[RestockRequest] = DeriveSchema.gen[RestockRequest]
}
case class StockReply(sku: String, quantity: Int)
object StockReply {
implicit val schema: Schema[StockReply] = DeriveSchema.gen[StockReply]
}
// Hand-written copies of the methods of service Inventory
object Inventory {
val GetStock =
Endpoint(Method.POST / "Inventory" / "GetStock")
.in[StockRequest]
.out[StockReply]
val Restock =
Endpoint(Method.POST / "Inventory" / "Restock")
.in[RestockRequest]
.out[StockReply]
}
Every message and every method is written twice, once in the .proto file and once in Scala. A field added to the .proto file and forgotten in the case class compiles without complaint, and the two descriptions drift apart one change at a time.
The sbt-zio-http-grpc plugin removes the Scala copy. It runs as part of protoc during compilation: ScalaPB generates the message case classes, and the plugin generates the endpoints and their schemas from the services of the same .proto file.
Prerequisites
The plugin runs inside sbt through sbt-protoc, the sbt plugin that runs protoc, and it builds on the message classes that ScalaPB generates. You need an sbt project; sbt-protoc downloads protoc itself. By the end of this guide, the project has these files:
build.sbt
project/plugins.sbt
src/main/protobuf/inventory.proto
src/main/protobuf/package.proto
src/main/scala/example/protobuf/InventoryServer.scala
src/main/scala/example/protobuf/InventoryClient.scala
This guide assumes you know how to define and implement an Endpoint. If not, start with Endpoint.
Adding the Plugin to the Build
The plugin is a protoc code generator, so it goes on the classpath of the build definition, next to sbt-protoc and the ScalaPB compiler plugin. In project/plugins.sbt:
addSbtPlugin("com.thesamet" % "sbt-protoc" % "1.0.8")
libraryDependencies ++= Seq(
"com.thesamet.scalapb" %% "compilerplugin" % "0.11.21",
"dev.zio" %% "sbt-zio-http-grpc" % "3.12.0",
)
Use the same version for sbt-zio-http-grpc as for zio-http, because the generated code calls the zio-http API of that version.
In build.sbt, we add zio-http and the ScalaPB runtime, and give sbt-protoc two targets: ScalaPB generates the message classes, and ZIOHttpGRPCGen generates the endpoints. Both write to the same directory:
libraryDependencies ++= Seq(
"dev.zio" %% "zio-http" % "3.12.0",
"com.thesamet.scalapb" %% "scalapb-runtime" % scalapb.compiler.Version.scalapbVersion % "protobuf",
)
Compile / PB.targets := Seq(
scalapb.gen(grpc = false) -> (Compile / sourceManaged).value / "scalapb",
zio.http.grpc.ZIOHttpGRPCGen -> (Compile / sourceManaged).value / "scalapb",
)
grpc = false turns off ScalaPB's own gRPC stubs, which the endpoints do not use. The scalapb-runtime dependency in the protobuf configuration makes scalapb/scalapb.proto available to protoc, which the next section imports.
Describing the Service in a .proto File
sbt-protoc compiles every .proto file under src/main/protobuf/. Our service has two methods, one to read the stock level of a product and one to add stock to it:
syntax = "proto3";
package shop;
service Inventory {
rpc GetStock (StockRequest) returns (StockReply);
rpc Restock (RestockRequest) returns (StockReply);
}
message StockRequest {
string sku = 1;
}
message RestockRequest {
string sku = 1;
int32 quantity = 2;
}
message StockReply {
string sku = 1;
int32 quantity = 2;
}
The plugin derives a ZIO Schema Schema for every request and response message, so the message classes must be plain case classes that ZIO Schema can derive. ScalaPB's defaults add a field of type UnknownFieldSet to every message and use Seq for repeated fields, and ZIO Schema derives neither. A second file sets the ScalaPB options that turn both off for the whole shop package:
syntax = "proto3";
package shop;
import "scalapb/scalapb.proto";
option (scalapb.options) = {
scope: PACKAGE
preserve_unknown_fields: false
collection_type: "List"
};
preserve_unknown_fields: false removes the unknownFields field, and collection_type: "List" makes repeated fields Lists. Without these options, the generated Schemas.scala fails to compile with errors such as Deriving schema for scala.collection.immutable.Seq[scala.Long] is not supported. package.proto declares no service, so the plugin generates nothing for it.
What the Plugin Generates
On sbt compile, the two targets write their files to target/scala-2.13/src_managed/main/scalapb/shop/inventory/. ScalaPB writes one case class per message (StockRequest.scala, RestockRequest.scala, StockReply.scala) and the file descriptor (InventoryProto.scala). The plugin adds two files next to them, in the same package shop.inventory.
The package is the .proto package followed by the file name without .proto, the same package ScalaPB uses for the messages. Inventory.scala holds one object per service, named after the service with its first letter in upper case, and one endpoint per method (shown here without its blank lines):
package shop.inventory
import shop.inventory.Schemas._
import shop.inventory._
import zio.http.endpoint.grpc.GRPC._
object Inventory{
import zio.http._
import zio.http.endpoint._
import zio.http.codec._
val GetStock=Endpoint(Method.POST / "Inventory" / "GetStock")
.in[StockRequest]
.out[StockReply](status = Status.Ok)
val Restock=Endpoint(Method.POST / "Inventory" / "Restock")
.in[RestockRequest]
.out[StockReply](status = Status.Ok)
}
Each method becomes a POST endpoint at /<service>/<method>, with the names exactly as the .proto file spells them. The method's request message is the endpoint's input and its response message is the output. For a method that streams its requests, the plugin uses Endpoint#inStream instead of Endpoint#in, and for a method that streams its responses, Endpoint#outStream instead of Endpoint#out.
Schemas.scala holds the schemas the endpoints need, one implicit Schema per request and response type:
package shop.inventory
object Schemas {
import zio.schema.{DeriveSchema, Schema}
implicit val StockRequestCodec: Schema[StockRequest] = DeriveSchema.gen[StockRequest]
implicit val StockReplyCodec: Schema[StockReply] = DeriveSchema.gen[StockReply]
implicit val RestockRequestCodec: Schema[RestockRequest] = DeriveSchema.gen[RestockRequest]
}
The import of zio.http.endpoint.grpc.GRPC._ in Inventory.scala brings in GRPC.fromSchema, which turns each of these schemas into the content codec of its endpoint. That codec reads and writes protobuf under the media type application/grpc.
Serving the Endpoints
The generated endpoints are ordinary Endpoint values, so we implement them like any other. The server keeps the stock levels in a Ref and implements both methods with Endpoint#implement:
package example.protobuf
import zio._
import zio.http._
import shop.inventory._
object InventoryServer extends ZIOAppDefault {
def routes(stock: Ref[Map[String, Int]]): Routes[Any, Response] =
Routes(
Inventory.GetStock.implement { request =>
stock.get.map(levels => StockReply(request.sku, levels.getOrElse(request.sku, 0)))
},
Inventory.Restock.implement { request =>
stock
.updateAndGet(levels => levels.updated(request.sku, levels.getOrElse(request.sku, 0) + request.quantity))
.map(levels => StockReply(request.sku, levels(request.sku)))
},
)
def run =
for {
stock <- Ref.make(Map("apple" -> 3))
_ <- Server.serve(routes(stock)).provide(Server.default)
} yield ()
}
The handlers receive the ScalaPB case classes and return them. Nothing in the server mentions protobuf: the codec comes with the generated endpoints.
The endpoints accept only application/grpc bodies. A request with a JSON body gets a 400 Bad Request whose body names the codec error MalformedBody:
$ curl -i -X POST http://localhost:8080/Inventory/GetStock \
-H 'Content-Type: application/json' --data '{"sku":"apple"}'
HTTP/1.1 400 Bad Request
content-type: text/html
Calling the Endpoints
A client built from the same generated endpoints encodes the requests and decodes the responses with the same codec. We run the endpoints through an EndpointExecutor pointed at the server:
package example.protobuf
import zio._
import zio.http._
import zio.http.endpoint._
import shop.inventory._
object InventoryClient extends ZIOAppDefault {
def run =
ZIO.scoped {
for {
client <- ZIO.service[Client]
executor = EndpointExecutor(client, url"http://localhost:8080")
before <- executor(Inventory.GetStock(StockRequest("apple")))
_ <- Console.printLine(s"Before: $before")
after <- executor(Inventory.Restock(RestockRequest("apple", 5)))
_ <- Console.printLine(s"After: $after")
} yield ()
}.provide(Client.default)
}
With the server running, the client reads the stock of apple, adds five, and prints both replies:
Before: StockReply(apple,3)
After: StockReply(apple,8)
What the Endpoints Send and Accept
The generated endpoints speak plain HTTP, not the gRPC protocol. Each call is one HTTP POST whose body is the encoded message, with the content type application/grpc. The body has no gRPC length prefix, and the response has no gRPC trailers. To see the bytes, we send the protobuf encoding of StockRequest("apple") with curl, after the client run above:
$ curl -s -X POST http://localhost:8080/Inventory/GetStock \
-H 'Content-Type: application/grpc' --data-binary $'\x0a\x05apple' | xxd
00000000: 0a05 6170 706c 6510 08 ..apple..
The response body is the bare StockReply: field 1 holds the string apple and field 2 the number 8.
The bodies are encoded by ZIO Schema's protobuf codec from the derived schemas, not by ScalaPB. That codec numbers the fields of a message by their position in the case class, and it has its own encoding for optional values, collections, enums, and oneofs. Its bytes are the same as the bytes of the .proto encoding only for messages like the ones in this guide, whose fields are all of type string, bool, int32, int64, float, or double and are numbered 1, 2, 3, and so on in the order they are declared. For any other message, such as one with a nested message, an optional or repeated field, an enum, a oneof, or a gap in its field numbers, call the endpoints with a ZIO HTTP client built from the same generated endpoints, as in the previous section.
Which .proto Layouts the Plugin Supports
The plugin expects a particular layout of the .proto files. For example, a file that declares two services makes protoc fail:
shop/inventory/Schemas.scala: Tried to write the same file twice.
The rules are:
- Declare one service per
.protofile. The plugin writes oneSchemas.scalaper service into the package of the file, so the error above appears when a file declares two services. - Declare the request and response messages of a service in the same file as the service, and import no other
.protofile there. The plugin turns each import into a Scala import named after the imported file, such asimport shop.common.proto._forimport "common.proto";, and that import does not compile. - Keep ScalaPB options in a separate file with
scope: PACKAGE, aspackage.protodoes in this guide. That file declares no service, so the import rule above does not apply to it. - Avoid
bytesfields in request and response messages. ScalaPB generates them asByteString, and ZIO Schema cannot derive a schema forByteString.
Running the Example
All code from this guide is in the standalone sbt project zio-http-example-protobuf-endpoints. From that folder, start the server:
sbt "runMain example.protobuf.InventoryServer"
In a second terminal, run the client:
sbt "runMain example.protobuf.InventoryClient"
The server listens on port 8080.
Going Further
- Endpoint covers what we can do with the generated endpoints, such as adding errors, middleware, or OpenAPI documentation.
- Binary Codecs shows how ZIO Schema derives the protobuf codec and the other binary codecs.
- OpenAPI codegen sbt plugin generates endpoints from OpenAPI files instead of
.protofiles.