sbagin13
sbagin13

Reputation: 115

How to create an endpoint with a Rust keyword as a query dynamic parameter?

I use the Rocket library and I need to create an endpoint which contains the dynamic parameter "type", a keyword.

I tried something like this but it does not compile:

#[get("/offers?<type>")]
pub fn offers_get(type: String) -> Status {
    unimplemented!()
}

compiler error:

error: expected argument name, found keyword `type`

Is it possible to have a parameter named "type" in rocket? I can't rename the parameter because of the specification I'm following.

Upvotes: 7

Views: 796

Answers (1)

TSB99X
TSB99X

Reputation: 3404

There is a known limitation for naming query parameters same as reserved keywords. It is highlighted in documentation on topic of Field Renaming. It does mention how to solve your problem with a little bit of extra code. Example for your use case:

use rocket::request::Form;

#[derive(FromForm)]
struct External {
    #[form(field = "type")]
    api_type: String
}

#[get("/offers?<ext..>")]
fn offers_get(ext: Form<External>) -> String {
    format!("type: '{}'", ext.api_type)
}

For GET request of /offers?type=Hello,%20World! it should return type: 'Hello, World!'

Upvotes: 8

Related Questions