Form Field Filters

Johannes Rudolph edited this page Aug 14, 2013 · 2 revisions

. . . Deprecation Note

This documentation is for release 0.9.0 (from 03/2012), which is built against Scala 2.9.1 and Akka 1.3.1 (see Requirements for more information). Most likely, this is not the place you want to look for information. Please turn to the main spray site at for more information about other available versions.

. . .

The formField/formFields directives filter on the existence of form fields in the incoming request and extract their values, either as a String or already converted to another type. The singular variant (formField) takes only one argument, the plural one (formFields) several. Every argument is of type FieldMatcher and normally triggers the extraction of the corresponding form field value.

Both variants accept the same mini-DSL as their parameter/parameters counterparts, so you might want to check out the chapter on Parameter Filters for details on how something like this works:

formFields("name"?, 'firstname, 'age ? 32) { (name, firstname, age) =>
  ... // name is an Option[String], firstName is a String and age is an Int

The formFields directives work with application/x-www-form-urlencoded form content as well as multipart/form-data. If you'd like to extract a form field directly into your custom type T you need to bring an implicit Deserializer and/or an Unmarshaller[T] in scope, depending on whether you'd like to extract application/x-www-form-urlencoded form fields or multipart/form-data, respectively.

spray comes with predefined converters for the following types Int, Long, Double, Float, Short, Byte, Boolean, Symbol. If there is an error during the type conversion the request will be rejected with a MalformedFormFieldRejection, which will, by default, trigger a 400 Bad Request error response with a respective informational text in the body.

Extracting all fields at once

In addition to extracting individual fields you can also extract the complete form (i.e. all fields) at once, e.g. for application/x-www-form-urlencoded form content with:

content(as[FormData]) { formData =>

and for multipart/form-data:

content(as[MultipartFormData]) { formData =>

Note that this requires your application to handle the verification of all fields as well as their type conversion itself, which is why the higher-level formFields directives are usually easier to work with.