0

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?

Finlay Weber
  • 2,989
  • 3
  • 17
  • 37
  • Please include a [mre] if you want debugging help. – cafce25 Dec 24 '22 at 10:51
  • 1
    According to your error message, this might work: `http://localhost:3000/greet?Male`. But I agree with @cafce25, this entire discussion is pretty pointless if you don't show us the actual code that processes the URL parameters. – Finomnis Dec 24 '22 at 11:02

1 Answers1

1

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.

kmdreko
  • 42,554
  • 6
  • 57
  • 106