Query Strings

Query strings are handled just like forms. A query string can be parsed into any structure that implements the FromForm trait. They are matched against by appending a ? to the path followed by a static query string or a dynamic parameter <param>.

For instance, say you change your mind and decide to use query strings instead of POST forms for new todo tasks in the previous forms example, reproduced below:

  1. #[derive(FromForm)]
  2. struct Task { .. }
  3. #[post("/todo", data = "<task>")]
  4. fn new(task: Form<Task>) -> String { ... }

Rocket makes the transition simple: simply declare <task> as a query parameter as follows:

  1. #[get("/todo?<task>")]
  2. fn new(task: Task) -> String { ... }

Rocket will parse the query string into the Task structure automatically by matching the structure field names to the query parameters. If the parse fails, the request is forwarded to the next matching route. Parse failures can be captured on a per-field or per-form basis.

To catch failures on a per-field basis, use a type of Option or Result for the given field:

  1. #[derive(FromForm)]
  2. struct Task<'r> {
  3. description: Result<String, &'r RawStr>,
  4. complete: Option<bool>
  5. }

To catch failures on a per-form basis, change the type of the query string target to either Option or Result:

  1. #[get("/todo?<task>")]
  2. fn new(task: Option<Task>) { ... }

For a concrete illustration on how to handle query parameters, see the query_params example.