http4s
02 / 02

http4s Fundamentals: HttpRoutes, Effects & Pattern Matching

http4s: HttpRoutes, Effects & Pattern Matching

http4s is a purely functional, type-safe HTTP library for Scala, typically integrated with an effect system like Cats Effect. Requests and responses are modeled as immutable, pure values -- constructing or transforming one performs no side effect.

Defining Routes

val userRoutes: HttpRoutes[IO] = HttpRoutes.of[IO] {
  case GET -> Root / "users" / IntVar(id) =>
    Ok(User(id, "Ada").asJson)

  case req @ POST -> Root / "users" =>
    for {
      input <- req.as[CreateUserInput]
      user  <- createUser(input)
      resp  <- Created(user.asJson)
    } yield resp
}

HttpRoutes[F] as a Pure Function

HttpRoutes[F] is essentially Request[F] => F[Option[Response[F]]] -- a pure function (wrapped in an effect type) that either produces a response or indicates no match, letting routes be composed and combined functionally.

Decoding Request Bodies

The EntityDecoder[F, A] type class (commonly paired with a JSON library like Circe) lets a handler call req.as[MyType] to decode the body into a typed Scala value -- decoding failures represented functionally, not via thrown exceptions.

Streaming Bodies With fs2

Request/response bodies are represented as an fs2 Stream, processed chunk by chunk rather than requiring the whole body to be buffered in memory upfront -- valuable for large uploads/downloads or long-lived streaming responses.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free