1

I'm starting to learn Http4s, at work we may need to migrate Rest APIs implemented with Akka Http to Http4s.

As an example I can define a custom directive like this:

trait CustomDirectives {

  def extractUUID: Directive1[UUID] = {
    path(Segment).flatMap { maybeuuid =>
      Try(UUID.fromString(maybeuuid)) match {
        case Success(result) => provide(result)
        case Failure(_) =>
          complete(StatusCodes.BadRequest, s"Invalid uuid: $maybeuuid")
      }
    }
  }

}

So everytime I want to extract an UUID and validate it I can use this directive. We have other custom directives to make some processing on headers, and many more.

Is there anything similar to akka custom directives but in Http4s?

M.G.
  • 369
  • 1
  • 14
  • 1
    I suggest migrating from Akka HTTP DSL to e.g. Tapir first (1.0 released today!), and then swapping the interpreter. It will be so much easier. – Mateusz Kubuszok Jun 15 '22 at 09:01

1 Answers1

2

This is described in Handling Path Parameters section of the documentation

// standard Scala extractor, matching String against UUID
object UUIDVar {
  def unapply(maybeuuid: String): Option[UUID] =
    Try(UUID.fromString(maybeuuid)).toOption
}

val usersService = HttpRoutes.of[IO] {
  // just use extractor in pattern matching
  case GET -> Root / "users" / UUIDVar(uuid) =>
    Ok(useUUIDForSth(uuid))
}

However, personally, I find it easier to describe endpoints with libraries like Tapir or Endpoint4s since their DSL seem more intuitive to me and I am not coupling my code with a particular implementation.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64