Skip to main content

Part 3: JSON Bodies

So far, our API answers with plain text, which is easy for people to read but awkward for programs. In this part, we switch every book response to JSON, the usual format of REST APIs, and add a POST /books route that reads a new book from a JSON request body. ZIO HTTP does the conversion between case classes and JSON for us, as long as each case class has a schema: a description of its fields that ZIO Schema derives automatically.

1. Derive a Schema for Each Type​

ZIO Schema comes with ZIO HTTP, so there is nothing to add to build.sbt. To give Book a schema, add a companion object right below the Book case class (the snippet repeats the case class for context) that derives one. A client that creates a book doesn't know its id yet (the server assigns it), so we also add a NewBook type for the request body, without an id field:

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

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]
}

DeriveSchema.gen[Book] inspects the fields of Book at compile time and builds a Schema[Book]. We declare it as an implicit val inside the companion object, so Scala finds it automatically wherever a Schema[Book] is needed; this includes List[Book], whose schema Scala builds from the schema of Book.

2. Answer with JSON​

Body.json encodes any value that has a schema as a JSON body. We wrap it in a small helper inside object BooksApp, because every JSON answer also needs a content-type: application/json header, which tells the client how to read the body:

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

Line by line:

  • jsonResponse[A](status: Status, value: A) works for any type A: a Book, a List[Book], and later an error message.
  • (implicit schema: Schema[A]) asks Scala to find the schema of A, such as the one we just derived for Book.
  • Response(status, body = Body.json(value)) builds a response with the given status and the value encoded as JSON.
  • Response#contentType(MediaType.application.json) adds the content-type: application/json header to the response.
note

Body.json marks the body itself as JSON, but a Response built with Response(status, body = ...) does not copy that into its headers, so we set the header ourselves.

With the helper in place, the two GET routes change only in their last expression. GET /books answers with the list of matching books:

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

GET /books/{id} answers with the book it finds:

Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
books.find(_.id == id) match {
case Some(book) => jsonResponse(Status.Ok, book)
case None => Response.notFound
}
}

The describe helper from part 2 is no longer used, so you can delete it.

3. Read a JSON Request Body​

Now let's accept new books. A POST /books request carries the new book as JSON in its body. Body#asJson decodes the body into any type that has a schema, but decoding can fail: the body may not be JSON at all, or a field may be missing. That is why Body#asJson returns a ZIO effect, a description of work that either succeeds with a value or fails with an error, instead of a plain value. Add this route to the Routes(...) list:

Method.POST / "books" -> handler { (req: Request) =>
for {
newBook <- req.body.asJson[NewBook].orElseFail(Response.badRequest)
book = Book(books.size + 1, newBook.title, newBook.author, newBook.year)
} yield jsonResponse(Status.Created, book)
}

Line by line:

  • Method.POST / "books" matches POST requests to /books; a GET to the same path still goes to our listing route.
  • req.body.asJson[NewBook] is an effect that decodes the body into a NewBook, or fails with an exception when the body is not a valid NewBook.
  • ZIO#orElseFail(Response.badRequest) replaces that exception with a 400 Bad Request response. Remember that Server.serve needs every failure to be a Response; this line makes it so.
  • for { ... } yield ... chains the steps: decode the body, then build the book, then answer. If decoding fails, the remaining steps are skipped and the server sends the 400 response.
  • Book(books.size + 1, ...) gives the new book the next id.
  • jsonResponse(Status.Created, book) answers 201 Created, the status REST APIs use for a successfully created resource, with the new book as JSON.

Notice that a handler can return either a plain Response, as in our GET routes, or an effect that produces a Response, as here. ZIO HTTP accepts both.

4. Run It​

Restart the server with sbt run and fetch book 1:

curl -i localhost:8080/books/1

The book now comes back as JSON, with the matching content-type header:

HTTP/1.1 200 OK
content-type: application/json
content-length: 60

{"id":1,"title":"Dune","author":"Frank Herbert","year":1965}

Next, create a book. The -d flag sends a request body and makes curl use POST:

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

The server decodes the body and answers 201 Created with the new book and its id:

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

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

Now send a body that is missing two fields:

curl -i -X POST localhost:8080/books -d '{"title":"Snow Crash"}'

Decoding fails, so ZIO#orElseFail turns the failure into 400 Bad Request:

HTTP/1.1 400 Bad Request
content-length: 0

Finally, ask for the book we just created:

curl -i localhost:8080/books/4

The answer is 404 Not Found. Our POST route built the new book and sent it back, but books is a fixed List, so the book is never saved:

HTTP/1.1 404 Not Found
content-length: 0
The complete BooksApp.scala at the end of part 3, with the routes from parts 1 and 2
zio-http-example-rest-api-tutorial/src/main/scala/example/restapi/part3/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.part3.BooksApp"

package example.restapi.part3

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

/**
* Build Your First REST API — Part 3: JSON Bodies
*
* Answers with JSON instead of text, and reads a new book from the JSON body of
* `POST /books`. The new book is not saved yet: part 4 adds storage.
*/
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]
}

object BooksApp extends ZIOAppDefault {

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

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[Any, 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)
val matching = books.filter(book => author.forall(_ == book.author)).take(limit)
jsonResponse(Status.Ok, matching)
},
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
books.find(_.id == id) match {
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 = Book(books.size + 1, newBook.title, newBook.author, newBook.year)
} yield jsonResponse(Status.Created, book)
},
)

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

Recap​

In this part, we derived a Schema for each case class with DeriveSchema.gen, answered with JSON through Body.json, and decoded a JSON request body with Body#asJson. We also met our first failure: decoding can fail, and ZIO#orElseFail turned that failure into a 400 Bad Request response.

In Part 4: A Books Service, we keep the books in a service that can change over time, so the books we create are saved.