Skip to main content

Part 4: A Books Service

In part 3, POST /books answers 201 Created but forgets the book right away, because our books live in a fixed List. In this part, we move the books into a service: a small component with its own interface that owns the data and can change it safely while many requests run at the same time. We then hand the service to our routes with a ZLayer, ZIO's way of building a dependency once and giving it to the code that needs it.

1. Describe the Service​

We start with the interface: a trait that lists what the rest of the app may do with books. Add it below the NewBook companion object:

import zio._
import zio.http._
import zio.schema.{DeriveSchema, Schema}

// Book and NewBook, with their schemas, are unchanged from part 3.
final case class Book(id: Int, title: String, author: String, year: Int)
object Book { implicit val schema: Schema[Book] = DeriveSchema.gen[Book] }
final case class NewBook(title: String, author: String, year: Int)
object NewBook { implicit val schema: Schema[NewBook] = DeriveSchema.gen[NewBook] }

trait BookRepo {
def all: UIO[List[Book]]
def get(id: Int): UIO[Option[Book]]
def add(newBook: NewBook): UIO[Book]
}

Each method returns a UIO, a ZIO effect that cannot fail. all lists the books, get looks one up, and add saves a new book and returns it with its id. The handlers depend only on this trait, not on how the books are stored, which is what lets us swap the storage later, for example for a database.

2. Implement It with a Ref​

Our first implementation keeps the books in memory, in a Ref. A Ref is a mutable reference that ZIO updates atomically, so two requests that add a book at the same moment never overwrite each other. Add this class below the trait:

final case class InMemoryBookRepo(books: Ref[Map[Int, Book]]) extends BookRepo {

def all: UIO[List[Book]] =
books.get.map(_.values.toList.sortBy(_.id))

def get(id: Int): UIO[Option[Book]] =
books.get.map(_.get(id))

def add(newBook: NewBook): UIO[Book] =
books.modify { current =>
val id = if (current.isEmpty) 1 else current.keys.max + 1
val book = Book(id, newBook.title, newBook.author, newBook.year)
(book, current + (id -> book))
}
}

Line by line:

  • books: Ref[Map[Int, Book]] holds every book, keyed by its id.
  • books.get reads the current map; all turns it into a list sorted by id, and get looks one id up.
  • books.modify { current => ... } reads the map and writes a new one in a single atomic step. The function returns a pair: the first element (book) becomes the result of add, and the second (current + (id -> book)) becomes the new content of the Ref.
  • current.keys.max + 1 picks the next free id. Because it runs inside modify, two concurrent add calls can never pick the same id.

3. Build It with a ZLayer​

A ZLayer describes how to build a service. Ours creates a Ref that starts with the three books from part 2, then wraps it in an InMemoryBookRepo. Add a companion object for the class:

object InMemoryBookRepo {

val initialBooks: List[Book] =
List(
Book(1, "Dune", "Frank Herbert", 1965),
Book(2, "Neuromancer", "William Gibson", 1984),
Book(3, "Count Zero", "William Gibson", 1986),
)

val layer: ULayer[BookRepo] =
ZLayer.fromZIO(
Ref.make(initialBooks.map(book => book.id -> book).toMap).map(InMemoryBookRepo(_)),
)
}

Ref.make(...) is an effect that creates the Ref with its first value, ZIO#map(InMemoryBookRepo(_)) wraps the Ref in our implementation, and ZLayer.fromZIO(...) turns that effect into a layer. Its type, ULayer[BookRepo], says the layer needs nothing, cannot fail, and produces a BookRepo. The fixed books list inside object BooksApp is no longer needed, so you can delete it.

4. Use the Service in the Handlers​

A handler asks for the service with ZIO.serviceWithZIO[BookRepo], which takes the BookRepo from the environment and calls one of its methods. GET /books now reads all books from the service and filters them as before:

Method.GET / "books" -> handler { (req: Request) =>
val author = req.queryParam("author")
val limit = req.queryOrElse[Int]("limit", 10)
ZIO.serviceWithZIO[BookRepo](_.all).map { books =>
val matching = books.filter(book => author.forall(_ == book.author)).take(limit)
jsonResponse(Status.Ok, matching)
}
}

ZIO.serviceWithZIO[BookRepo](_.all) is an effect that produces the list of books, and ZIO#map turns that list into the response. GET /books/{id} works the same way, with BookRepo#get:

Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
ZIO.serviceWithZIO[BookRepo](_.get(id)).map {
case Some(book) => jsonResponse(Status.Ok, book)
case None => Response.notFound
}
}

POST /books now saves the decoded book with add and answers with the stored book:

Method.POST / "books" -> handler { (req: Request) =>
for {
newBook <- req.body.asJson[NewBook].orElseFail(Response.badRequest)
book <- ZIO.serviceWithZIO[BookRepo](_.add(newBook))
} yield jsonResponse(Status.Created, book)
}

5. Provide the Layer​

Because the handlers now ask for a BookRepo, the type of our routes changes. The first type parameter of Routes lists what the routes need from the environment. Change the type of routes and keep the four routes we wrote above (GET /health, GET /books, GET /books/{id} and POST /books) inside it:

val routes: Routes[BookRepo, Response] =
Routes(
// the four routes from above
)

Server.serve(routes) now needs both a Server and a BookRepo, so we provide both layers in run:

def run = Server.serve(routes).provide(Server.default, InMemoryBookRepo.layer)

ZIO#provide builds each layer once when the program starts. Every request then shares the same InMemoryBookRepo, and therefore the same Ref, which is exactly what lets a book created by one request show up in the next one.

tip

Try deleting InMemoryBookRepo.layer from provide. The program no longer compiles, and the error message names the missing BookRepo. ZIO checks at compile time that every service the routes need is provided.

6. Run It​

Restart the server with sbt run and create a book again:

curl -i -X POST localhost:8080/books -d '{"title":"Snow Crash","author":"Neal Stephenson","year":1992}'

The answer looks the same as in part 3:

HTTP/1.1 201 Created
content-type: application/json
content-length: 68

{"id":4,"title":"Snow Crash","author":"Neal Stephenson","year":1992}

This time, the book is saved. Ask for it:

curl localhost:8080/books/4

The server finds it:

{"id":4,"title":"Snow Crash","author":"Neal Stephenson","year":1992}

Now list every book:

curl localhost:8080/books

The list has four books, ending with the new one:

[{"id":1,"title":"Dune","author":"Frank Herbert","year":1965},{"id":2,"title":"Neuromancer","author":"William Gibson","year":1984},{"id":3,"title":"Count Zero","author":"William Gibson","year":1986},{"id":4,"title":"Snow Crash","author":"Neal Stephenson","year":1992}]

The books live in memory, so restarting the server brings back the three original books.

The complete BooksApp.scala at the end of part 4, with the service, the layer and all four routes
zio-http-example-rest-api-tutorial/src/main/scala/example/restapi/part4/BooksApp.scala
//> using scala 2.13.18
//> using dep dev.zio::zio-http:3.12.0
// Run from this folder: scala-cli run BooksApp.scala
// Or from zio-http-example-rest-api-tutorial: sbt "runMain example.restapi.part4.BooksApp"

package example.restapi.part4

import zio._
import zio.http._
import zio.schema.{DeriveSchema, Schema}

/**
* Build Your First REST API — Part 4: A Books Service
*
* Moves the books into a `BookRepo` service backed by a `Ref`, provides it with
* a `ZLayer`, and saves the books that `POST /books` creates.
*/
final case class Book(id: Int, title: String, author: String, year: Int)

object Book {
implicit val schema: Schema[Book] = DeriveSchema.gen[Book]
}

final case class NewBook(title: String, author: String, year: Int)

object NewBook {
implicit val schema: Schema[NewBook] = DeriveSchema.gen[NewBook]
}

trait BookRepo {
def all: UIO[List[Book]]
def get(id: Int): UIO[Option[Book]]
def add(newBook: NewBook): UIO[Book]
}

final case class InMemoryBookRepo(books: Ref[Map[Int, Book]]) extends BookRepo {

def all: UIO[List[Book]] =
books.get.map(_.values.toList.sortBy(_.id))

def get(id: Int): UIO[Option[Book]] =
books.get.map(_.get(id))

def add(newBook: NewBook): UIO[Book] =
books.modify { current =>
val id = if (current.isEmpty) 1 else current.keys.max + 1
val book = Book(id, newBook.title, newBook.author, newBook.year)
(book, current + (id -> book))
}
}

object InMemoryBookRepo {

val initialBooks: List[Book] =
List(
Book(1, "Dune", "Frank Herbert", 1965),
Book(2, "Neuromancer", "William Gibson", 1984),
Book(3, "Count Zero", "William Gibson", 1986),
)

val layer: ULayer[BookRepo] =
ZLayer.fromZIO(
Ref.make(initialBooks.map(book => book.id -> book).toMap).map(InMemoryBookRepo(_)),
)
}

object BooksApp extends ZIOAppDefault {

def jsonResponse[A](status: Status, value: A)(implicit schema: Schema[A]): Response =
Response(status, body = Body.json(value)).contentType(MediaType.application.json)

val routes: Routes[BookRepo, Response] =
Routes(
Method.GET / "health" -> handler(Response.text("OK")),
Method.GET / "books" -> handler { (req: Request) =>
val author = req.queryParam("author")
val limit = req.queryOrElse[Int]("limit", 10)
ZIO.serviceWithZIO[BookRepo](_.all).map { books =>
val matching = books.filter(book => author.forall(_ == book.author)).take(limit)
jsonResponse(Status.Ok, matching)
}
},
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
ZIO.serviceWithZIO[BookRepo](_.get(id)).map {
case Some(book) => jsonResponse(Status.Ok, book)
case None => Response.notFound
}
},
Method.POST / "books" -> handler { (req: Request) =>
for {
newBook <- req.body.asJson[NewBook].orElseFail(Response.badRequest)
book <- ZIO.serviceWithZIO[BookRepo](_.add(newBook))
} yield jsonResponse(Status.Created, book)
},
)

def run = Server.serve(routes).provide(Server.default, InMemoryBookRepo.layer)
}

Recap​

In this part, we moved our data into a BookRepo service, implemented it with a Ref that ZIO updates atomically, and built it with a ZLayer. The handlers reach the service with ZIO.serviceWithZIO, the routes' type Routes[BookRepo, Response] records that need, and provide satisfies it once for the whole server.

In Part 5: Error Responses, we make failures explicit, so that every bad request gets a clear JSON answer.