gengteng / axum-valid

axum-valid is a library that provides data validation extractors for the Axum web framework. It integrates validator, garde and validify, three popular validation crates in the Rust ecosystem, to offer convenient validation and data handling extractors for Axum applications.
MIT License
103 stars 4 forks source link

Recommendation for modifying response #25

Closed lucasyvas closed 2 months ago

lucasyvas commented 3 months ago

Great library! I'm trying to use it for an API that returns JSON and I'm wondering what the preferred way would be to consume the error string yielded from the Valid extractor, but transform it into a JSON response. Ideally I'd like to do this in one way for anything that the extractor invalidates on any route.

gengteng commented 3 months ago

To return JSON responses when the Valid extractor fails, enable the into_json feature for the axum-valid crate. Additionally, if you want to change the HTTP response status code to 422 when validation errors occur, you can enable the 422 feature. If you have more complex requirements, feel free to discuss them!

[dependencies]
axum-valid = { version = "0.18.0", features = ["into_json", "422"] }
lucasyvas commented 2 months ago

To return JSON responses when the Valid extractor fails, enable the into_json feature for the axum-valid crate. Additionally, if you want to change the HTTP response status code to 422 when validation errors occur, you can enable the 422 feature. If you have more complex requirements, feel free to discuss them!

[dependencies]
axum-valid = { version = "0.18.0", features = ["into_json", "422"] }

Does it have to be enabled somehow? It's still returning a plain text response (I use validator). Beyond that, what I really wanted to do is to customize the format of returned JSON, setting the error message to a specific JSON property. Basically, I want the message string, but full control over the body. I could probably use middleware to do this if I really had to but I'm not sure.

gengteng commented 2 months ago

After enabling the into_json feature, validation errors will return HTTP responses with a Content-Type of application/json. The JSON body format will depend on the validation library you are using, such as validator, garde, or validify.

If you need to customize the JSON structure, you can indeed use middleware to modify the response uniformly. Alternatively, you can define a custom error type and use WithRejection from the axum-extra crate. All extractors in axum-valid are compatible with WithRejection, allowing for flexible error handling.

For more details, you might find PR #3 helpful, which discusses the use of WithRejection and provides some practical examples.

Hope this helps! If you have any more questions or need further assistance, feel free to ask!

lucasyvas commented 2 months ago

Thanks for the help! I'll give all these options a look.