In Akka HTTP, directives and routes are essential components for building web services. Directives define reusable pieces of route logic, encapsulating request handling and response generation. Routes are tree-like structures composed of directives that match incoming requests to appropriate handlers.
Directives can be nested and combined using combinators, allowing complex routing logic with minimal code. Custom directives can be created by extending existing ones or implementing new functionality. To implement a custom directive, define a function that takes necessary parameters and returns a Directive instance.
Example : A custom directive to validate an API key :
import akka.http.scaladsl.server.Directive1
import akka.http.scaladsl.server.directives._
def apiKeyValidation(apiKey: String): Directive1[String] = {
val validApiKey = "my-secret-key"
if (apiKey == validApiKey) provide(apiKey)
else reject(AuthorizationFailedRejection)
}
val route =
path("secure") {
headerValueByName("api-key") { apiKey =>
apiKeyValidation(apiKey) { _ =>
complete("Authorized access")
}
}
}?
This custom directive checks if the provided API key matches the valid one and either provides it downstream or rejects the request with an AuthorizationFailedRejection.