Actix-web, accessing query parameters untyped-ly

Hi,

so, i want to use actix-web to write a web backend. some of the endpoints need to accept query parameters (the ?part=of&the=url&that=looks&like=this). According to the actix-web docs, I should specify a struct that contains all the fields that could possibly occur, in order for actix to accept that request.

Unfortunately, i need to implement an already-existing API here, and there are many query fields i'll never need to read, and it's subject to ongoing change, so i'd rather not do that.

Is there a way to not have to statically specify all the fields and instead use a catch-all and get all the query parameters as a HashMap<&str, &str> or something like that?

found it myself; it seems it's possible to use HashMap or Vec as the generic type of Query like so:

async fn index(query: web::Query<std::collections::HashMap<(String, String)>>) -> impl Responder {
  //…
}
async fn index(query: web::Query<Vec<(String, String)>>) -> impl Responder {
  //…
}

the second one seems to preserve the order of arguments, is there a way to be sure of that?


Edit: additional note for anyone finding this via a search engine, it's also possible to use
HttpRequest as an extractor, which we can use to get everything else manually:

async fn index(req : HttpRequest) -> impl Responder {
  // e.g. you can now get the query string via
  req.query_string();
  // or even get the client's ip address like so
  req.connection_info().remote_addr();
}
1 Like

I think it's safe to rely on that. The Actix documentation mentions that it uses serde_urlencoded, which contains tests that assert the order of a deserialized Vec<(String, String)>.

1 Like

Thanks! :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.