formField

Description

Allows extracting a single Form field sent in the request. Data posted from HTML Forms is either of type application/x-www-form-urlencoded or of type multipart/form-data.

See formFields for an in-depth description.

Example

Scala
sourceval route =
  concat(
    formField("color") { color =>
      complete(s"The color is '$color'")
    },
    formField("id".as[Int]) { id =>
      complete(s"The id is '$id'")
    }
  )

// tests:
Post("/", FormData("color" -> "blue")) ~> route ~> check {
  responseAs[String] shouldEqual "The color is 'blue'"
}

Get("/") ~> Route.seal(route) ~> check {
  status shouldEqual StatusCodes.BadRequest
  responseAs[String] shouldEqual "Request is missing required form field 'color'"
}
Java
sourceimport akka.http.javadsl.server.Directives;

import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.formField;

final Route route = Directives.concat(
  formField("color", color ->
    complete("The color is '" + color + "'")
  ),
  formField(StringUnmarshallers.INTEGER, "id", id ->
    complete("The id is '" + id + "'")
  )
);

// tests:
final FormData formData = FormData.create(Pair.create("color", "blue"));
testRoute(route).run(HttpRequest.POST("/").withEntity(formData.toEntity()))
  .assertEntity("The color is 'blue'");

testRoute(route).run(HttpRequest.GET("/"))
  .assertStatusCode(StatusCodes.BAD_REQUEST)
  .assertEntity("Request is missing required form field 'color'");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.