method

Matches HTTP requests based on their method.

Signature

def method(httpMethod: HttpMethod): Directive0 

Description

This directive filters the incoming request by its HTTP method. Only requests with the specified method are passed on to the inner route. All others are rejected with a MethodRejectionMethodRejection, which is translated into a 405 Method Not Allowed response by the default RejectionHandler.

Example

Scala
sourceval route = method(HttpMethods.PUT) { complete("This is a PUT request.") }

// tests:
Put("/", "put content") ~> route ~> check {
  responseAs[String] shouldEqual "This is a PUT request."
}

Get("/") ~> Route.seal(route) ~> check {
  status shouldEqual StatusCodes.MethodNotAllowed
  responseAs[String] shouldEqual "HTTP method not allowed, supported methods: PUT"
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.method;

final Route route = method(HttpMethods.PUT, () -> complete("This is a PUT request."));

testRoute(route)
    .run(HttpRequest.PUT("/").withEntity("put content"))
    .assertEntity("This is a PUT request.");

testRoute(route).run(HttpRequest.GET("/")).assertStatusCode(StatusCodes.METHOD_NOT_ALLOWED);