Using Warp’s query to handle GET array key values
Note: Generally it’s not a valid format. Avoid using the same key to pass array like values.
Warp will parse your query string into a
data structure using serialization. We will use this to parse into
Vec<(String, String)>
which allows us to have 2 of the same key. Then we’d
need to parse this down more but gets us the flexibility if we just need to pass
it on or if this format is the appropriate format. We could also use other
formats like into a struct and then using other serde libraries for parsing that
down if you need more control over the data structure.
You may need to pass multiple query keys to create an array of values for a key.
key=1&key=2
Note: Don’t do this but if you need to …
Using Warp’s query
To represent this in rust, the most flexible is creating a list of key values.
We can use warp::query::<Vec<(String, String>>()
to represent this.
let models = warp::path!("api" / "v1" / "models")
.and(warp::query::<Vec<(String, String)>>())
.and_then(|qs: Vec<(String, String)>| {
dbg!(qs);
warp::reply()
});
warp::serve(warp::get().and(models))
.run(([127, 0, 0, 1], 3030))
.await;
Test result
Then you can test it in the browser.
http://localhost:3030/api/v1/models?key=1&key=2
And should output the query string parameters to the terminal.
[Insert quality example here about how the dbg!
looks in the terminal to
inspire the reader to complete the project and see the success of their work.
Maybe the hint of their success will be enough.]