0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Routes and HttpRoutes

Define endpoints functionally.

What http4s Is

http4s is a purely functional HTTP library for Scala, built on cats-effect and fs2 streams. Requests and responses are immutable values, and effects are captured in a polymorphic effect type F[_] such as IO.

Instead of mutating a servlet, you describe an HTTP service as a function from a request to an effectful optional response.

The HttpRoutes Type

The core abstraction is HttpRoutes[F], an alias for Kleisli[OptionT[F, *], Request[F], Response[F]]. The OptionT models a route that may not match, returning no response.

You rarely write that signature by hand. Instead you build routes with the HttpRoutes.of constructor and a partial function.

import cats.effect.IO
import org.http4s._
import org.http4s.dsl.io._

val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
  case GET -> Root / "hello" => Ok("hi")
}

All lessons in this course

  1. Routes and HttpRoutes
  2. Requests and Responses
  3. JSON Endpoints
  4. Serving the Application
← Back to Scala for Backend Engineering & Functional Programming