Search⌘ K
AI Features

Http4s Routes

Explore how to implement http4s routes in Scala for pure functional HTTP APIs. Learn route abstraction, JSON serialization, and handling database operations within routes.

Base for http4s routes

The routing DSL of http4s differs from the routing of Akka-HTTP. The latter makes it easier to model out a base for our routes.

Scala
val productRoutes: HttpRoutes[IO] = HttpRoutes.of[IO] {
case GET -> Root / "product" / id =>
???
case PUT -> Root / "product" / id =>
???
}
val productsRoutes: HttpRoutes[IO] = HttpRoutes.of[IO] {
case GET -> Root / "products" =>
???
case POST -> Root / "products" =>
???
}

As we can see, the DSL is closer to Scala syntax and quite easy to read. But before we move on to the details of each route, let’s think about how this can be modelled to become a bit more abstract.

Routing classes

While it is fine to have our routes bound to IO, it would be better to ...