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:
#[derive(FromForm)]
struct Task { .. }
#[post("/todo", data = "<task>")]
fn new(task: Form<Task>) -> String { ... }
Rocket makes the transition simple: simply declare <task>
as a query parameter as follows:
#[get("/todo?<task>")]
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:
#[derive(FromForm)]
struct Task<'r> {
description: Result<String, &'r RawStr>,
complete: Option<bool>
}
To catch failures on a per-form basis, change the type of the query string target to either Option
or Result
:
#[get("/todo?<task>")]
fn new(task: Option<Task>) { ... }
For a concrete illustration on how to handle query parameters, see the query_params example.