A Domain Specific Language (DSL) for building HTTP services in Scala with type-safe route definition, status code generation, and composable request/response handling
npx @tessl/cli install tessl/maven-org-http4s--http4s-dsl_2-13@0.23.0The http4s-dsl package provides a Domain Specific Language (DSL) for building HTTP services in Scala. It offers intuitive syntax for route definition using pattern matching on HTTP methods and paths, status code generation through named objects, and composable request/response handling with built-in support for content negotiation and entity encoding/decoding.
libraryDependencies += "org.http4s" %% "http4s-dsl" % "0.23.30"import org.http4s.dsl.io._For custom effect types:
import cats.effect.IO
import org.http4s.dsl.Http4sDsl
// Create DSL instance for your effect type
val dsl = Http4sDsl[IO]
import dsl._import cats.effect.IO
import org.http4s._
import org.http4s.dsl.io._
// Define routes using pattern matching
val routes = HttpRoutes.of[IO] {
case GET -> Root / "hello" =>
Ok("Hello, World!")
case GET -> Root / "users" / IntVar(userId) =>
Ok(s"User ID: $userId")
case POST -> Root / "users" =>
Created("User created")
case req @ POST -> Root / "data" =>
req.as[String].flatMap { body =>
Ok(s"Received: $body")
}
}The http4s-dsl is built around several key components:
Core HTTP method constants and path pattern matching for defining web service routes. Enables clean, readable route definitions using Scala's pattern matching syntax.
// HTTP Methods
val GET: Method.GET.type
val POST: Method.POST.type
val PUT: Method.PUT.type
val DELETE: Method.DELETE.type
val HEAD: Method.HEAD.type
val OPTIONS: Method.OPTIONS.type
val PATCH: Method.PATCH.type
val CONNECT: Method.CONNECT.type
val TRACE: Method.TRACE.type
// Route matching operators
val -> : impl.->.type // Method and path matcher
val → : impl.->.type // Unicode alias for ->
val ->> : impl.->>.type // Method enumeration matcherPath construction and variable extraction utilities for URL routing. Provides type-safe path segment matching and variable extraction from URL paths.
// Path components
val Path: Uri.Path.type
val Root: Uri.Path.Root.type
val / : impl./.type // Path segment separator
// Path extractors
val /: : impl./:.type // Path head/tail extractor
val IntVar: impl.IntVar.type // Integer path variable
val LongVar: impl.LongVar.type // Long path variable
val UUIDVar: impl.UUIDVar.type // UUID path variable
// File extensions
val ~ : impl.~.type // File extension extractorComplete set of HTTP status codes with fluent response generation API. Each status code provides type-safe methods for creating responses with or without bodies.
// 2xx Success responses
val Ok: Status.Ok.type
val Created: Status.Created.type
val Accepted: Status.Accepted.type
val NoContent: Status.NoContent.type
// 3xx Redirection responses
val MovedPermanently: Status.MovedPermanently.type
val Found: Status.Found.type
val SeeOther: Status.SeeOther.type
val NotModified: Status.NotModified.type
// 4xx Client error responses
val BadRequest: Status.BadRequest.type
val Unauthorized: Status.Unauthorized.type
val Forbidden: Status.Forbidden.type
val NotFound: Status.NotFound.type
// 5xx Server error responses
val InternalServerError: Status.InternalServerError.type
val NotImplemented: Status.NotImplemented.type
val ServiceUnavailable: Status.ServiceUnavailable.typeStatus Codes and Response Generation
Type-safe query parameter extraction and validation with support for optional parameters, multi-value parameters, and custom decoders.
val :? : impl.:?.type // Query parameter extractor
val +& : impl.+&.type // Multiple parameter combinator
// Query parameter matcher types
type QueryParamDecoderMatcher[T]
type OptionalQueryParamDecoderMatcher[T]
type QueryParamDecoderMatcherWithDefault[T]
type ValidatingQueryParamDecoderMatcher[T]
type FlagQueryParamMatcherAuthentication context extraction utilities for working with authenticated requests and user context.
// Authentication extractor
object as {
def unapply[F[_], A](ar: AuthedRequest[F, A]): Option[(Request[F], A)]
}Additional utilities for advanced pattern matching in route definitions.
// Conjunction extractor for pattern matching combinations
object & {
def unapply[A](a: A): Some[(A, A)]
}// Core path types
type Path = Uri.Path
type Root = Uri.Path.Root.type
// Method concatenation for multiple method matching
type MethodConcat = impl.MethodConcat
// Response generator base types
trait ResponseGenerator {
def status: Status
}
trait EntityResponseGenerator[F[_], G[_]] extends ResponseGenerator {
def liftG: G ~> F
def apply(): F[Response[G]]
def apply[A](body: A, headers: Header.ToRaw*): F[Response[G]]
}