Search code examples
rustrust-axum

How to use enums as a query parameter with Axum


I have an enum similar to:

#[derive(Debug, Deserialize, Serialize)]
pub enum Gender {
    Male,
    Female,
    NonBinary
}

and I a have an axum handler function which expects it to be passed in as Query(gender): Query<Gender>

But when I request the endpoint like this:

http://localhost:3000/greet?gender=Male

The page returns the following error message:

Failed to deserialize query string: invalid type: map, expected enum Gender

If I switch the params to use a struct instead everything works fine, which is why I know this is specifically an issue with enum serialization.

Any ideas how to fix?


Solution

  • You should use a struct as your query parameter type:

    #[derive(Debug, Deserialize, Serialize)]
    pub enum Gender {
        Male,
        Female,
        NonBinary
    }
    
    #[derive(Debug, Deserialize)]
    pub struct GreetParams {
        gender: Gender,
    }
    
    async fn greet_handler(Query(params): Query<GreetParams>) {}
    

    The reason you get an error is because ?gender=Male is parsed as a mapping of key-value pairs. Therefore, you need to use a mapped data structure that has named keys: something like BTreeMap<String, _>, HashMap<String, _>, or a struct.

    If I switch the params to use a struct instead everything works fine, which is why I know this is specifically an issue with enum serialization. Any ideas how to fix?

    There is nothing to fix; this is working as intended.