liveBook · Manning

Directive

As explained in Akka in Action, Second Edition

An Akka HTTP directive is a reusable routing component that extracts request information, applies conditions, or provides route behavior.

A directive is a reusable Akka HTTP routing component that shapes request processing. It can create paths, extract request data, filter routes, handle failures, or produce the final response. section 11.1.3

Directives can perform several routing operations:

  • Transform a request and pass it to an inner route. section 11.1.3
  • Filter requests, allowing alternative directives to handle unmatched methods or paths. section 11.1.3 section 11.1.4
  • Extract values such as parameters or the request URI for use by nested logic. section 11.1.3
  • Intercept results, reject requests, fail with exceptions, complete responses, or redirect requests. section 11.1.3

Selecting GET and POST behavior

A route can nest directives to respond differently to the same path. For `/ping`, `get { complete("pong") }` handles GET requests, while `post { complete("ping stored") }` handles POST requests. `concat` explicitly combines the alternatives; the older `~` operator also traverses alternatives but can silently drop a route when omitted. section 11.1.4

Completing and handling failures

`complete` can return a default `200 OK` text response or construct an `HttpResponse` with a status code, media type, headers, and entity. Wrapping a route with `handleExceptions` lets an `ExceptionHandler` convert failures into a controlled response, such as JSON containing the requested URI. section 11.1.4

$ curl localhost:8080/ping
pong

Run the minimal `/ping` route and verify its response with curl: the server returns `pong`. section 11.1.1

How Akka in Action, Second Edition covers it

How deep it goes
Explains directive operations, nesting, rejection, route alternatives, completion, and exception handling through runnable route examples.
Examples
Uses `/ping` GET and POST routes, nested `concat` paths, `complete`, curl requests, and an exception-handling route.
What it assumes
Assumes basic HTTP requests and responses while establishing routing primitives through a minimal `/ping` server.
What you can do after
Builds Akka HTTP routes that match paths and methods, extract request data, return responses, and handle failures.
How it connects
Connects directives with routes, request extraction, HTTP responses, exception handling, and the ActorSystem.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Akka in Action, Second Edition. The section links point to the parts of the book it draws on.