Closed lucasyvas closed 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"] }
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.
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!
Thanks for the help! I'll give all these options a look.
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.