Format

A route can specify the data format it is willing to accept or respond with using the format route parameter. The value of the parameter is a string identifying an HTTP media type. For instance, for JSON data, the string application/json can be used.

When a route indicates a payload-supporting method (PUT, POST, DELETE, and PATCH), the format route parameter instructs Rocket to check against the Content-Type header of the incoming request. Only requests where the Content-Type header matches the format parameter will match to the route.

As an example, consider the following route:

  1. #[post("/user", format = "application/json", data = "<user>")]
  2. fn new_user(user: Json<User>) -> T { ... }

The format parameter in the post attribute declares that only incoming requests with Content-Type: application/json will match new_user. (The data parameter is described in the next section.)

When a route indicates a non-payload-supporting method (GET, HEAD, and OPTIONS), the format route parameter instructs Rocket to check against the Accept header of the incoming request. Only requests where the preferred media type in the Accept header matches the format parameter will match to the route.

As an example, consider the following route:

  1. #[get("/user/<id>", format = "application/json")]
  2. fn user(id: usize) -> Json<User> { ... }

The format parameter in the get attribute declares that only incoming requests with application/json as the preferred media type in the Accept header will match user.