What is a default rejection for http methods not found?
This topic is based on a conversation between an anonymous user of Akka and our “Ask AI about Akka” bot in the documentation.
What is a default rejection for http methods not found?
This topic is based on a conversation between an anonymous user of Akka and our “Ask AI about Akka” bot in the documentation.
In Akka HTTP, if an HTTP request does not match any defined route, a default 404 Not Found
response is returned. However, if a request is filtered based on its HTTP method and it does not match the specified method, it is rejected with a MethodRejection
. This MethodRejection
is then translated into a 405 Method Not Allowed
response by the default RejectionHandler
.
Here is an example from the Akka HTTP documentation:
Scala:
val 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:
import static akka.http.javadsl.server.Directives.complete;
import static akka.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);
In these examples, the route only accepts PUT
requests. If a GET
request is made, it is rejected and a 405 Method Not Allowed
response is returned.
Sources: