Part 2: Path and Query Parameters
In this part, we give our API something to serve: a fixed list of books. We add two routes, GET /books, which lists books and can filter them with query parameters, and GET /books/{id}, which reads a book id from the path. For now, both answer with plain text; Part 3 switches them to JSON.
1. Model the Books
A REST API is about resources, and our resource is a book. Let's model it with a case class, which goes above object BooksApp, plus a fixed list of three books and a describe helper, which go inside it:
import zio._
import zio.http._
final case class Book(id: Int, title: String, author: String, year: Int)
// inside object BooksApp:
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 describe(book: Book): String =
s"${book.id}: ${book.title} by ${book.author} (${book.year})"
The Book case class holds the four fields of a book, books is our in-memory collection, and describe turns one book into a line of text such as 2: Neuromancer by William Gibson (1984).
2. List the Books with Query Parameters
Query parameters are the key=value pairs after the ? in a URL, as in /books?author=William%20Gibson&limit=1. They are optional by nature, so our route must work with or without them. We want two of them: author keeps only the books by that author, and limit caps the number of books returned.
To read them, the handler needs the request itself. When a handler is a function that takes a Request, ZIO HTTP passes the incoming request to it. Add this route to the Routes(...) list; routes in the list are separated by commas:
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)
Response.text(matching.map(describe).mkString("\n"))
}
Line by line:
handler { (req: Request) => ... }builds a handler from a function of the request.req.queryParam("author")returns the raw value ofauthoras anOption[String]:Some("William Gibson")when the parameter is present,Nonewhen it is not.req.queryOrElse[Int]("limit", 10)readslimitand converts it to anInt, falling back to10when the parameter is missing.author.forall(_ == book.author)istruefor every book when there is noauthorparameter, and only for matching books when there is one.Response.text(...)answers200 OKwith one line per book.
3. Look Up One Book with a Path Parameter
Path parameters are parts of the path itself, such as the 2 in /books/2. In REST APIs, they usually identify one resource. ZIO HTTP describes a path parameter with a typed segment: int("id") matches one path segment that is a whole number and hands it to the handler as an Int. Add this route to the Routes(...) list:
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
books.find(_.id == id) match {
case Some(book) => Response.text(describe(book))
case None => Response.notFound
}
}
Line by line:
Method.GET / "books" / int("id")matchesGET /books/1,GET /books/2and so on, but notGET /books/abc.handler { (id: Int, _: Request) => ... }receives the path parameter first and the request second; we name the request_because this route does not use it.books.find(_.id == id)looks the book up and returns anOption[Book].Response.notFoundanswers404 Not Foundwhen no book has that id.
Notice that the types line up: the route pattern contains one int segment, so the handler takes one Int before the request. If the pattern had two parameters, the handler would take both, in order.
4. Run It
Our Routes(...) list now holds three routes: GET /health, GET /books and GET /books/{id}. Start the server with sbt run, then list every book:
curl localhost:8080/books
The server answers with all three books:
1: Dune by Frank Herbert (1965)
2: Neuromancer by William Gibson (1984)
3: Count Zero by William Gibson (1986)
Next, filter by author. The space in the author's name is written as %20, the URL encoding of a space:
curl "localhost:8080/books?author=William%20Gibson"
Only William Gibson's books remain:
2: Neuromancer by William Gibson (1984)
3: Count Zero by William Gibson (1986)
Then cap the number of books with limit:
curl "localhost:8080/books?limit=1"
Only the first book comes back:
1: Dune by Frank Herbert (1965)
Now look up one book by its id:
curl localhost:8080/books/2
The server answers with book 2:
2: Neuromancer by William Gibson (1984)
Finally, try an id that does not exist, and an id that is not a number:
curl -i localhost:8080/books/42
curl -i localhost:8080/books/abc
Both answer 404 Not Found with an empty body. The first comes from our Response.notFound; the second never reaches our handler, because abc does not match the int("id") segment, so no route matches at all:
HTTP/1.1 404 Not Found
content-length: 0
Try curl "localhost:8080/books?limit=abc". It returns all three books, because Request#queryOrElse falls back to the default when the value is missing or cannot be converted to an Int. A caller who made a typo never finds out. We fix this in Part 5.
The complete BooksApp.scala at the end of part 2, with the /health route from part 1
//> 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.part2.BooksApp"
package example.restapi.part2
import zio._
import zio.http._
/**
* Build Your First REST API — Part 2: Path and Query Parameters
*
* Lists books from a fixed list, filters them with the `author` and `limit`
* query parameters, and looks one book up by the `id` in its path.
*/
final case class Book(id: Int, title: String, author: String, year: Int)
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 describe(book: Book): String =
s"${book.id}: ${book.title} by ${book.author} (${book.year})"
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)
Response.text(matching.map(describe).mkString("\n"))
},
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
books.find(_.id == id) match {
case Some(book) => Response.text(describe(book))
case None => Response.notFound
}
},
)
def run = Server.serve(routes).provide(Server.default)
}
Recap
In this part, we read input from the request in two ways. A typed path segment such as int("id") matches part of the path and passes it to the handler as a typed value; Request#queryParam and Request#queryOrElse read optional query parameters.
In Part 3: JSON Bodies, we replace the plain-text answers with JSON and accept new books in a POST request.