Validating Json Request in axumAyush Singh January 17, 2023 #rust #axum #web
I have been playing around with axum, and it has been quite a fun web framework. While using it, I came across what is a relatively common use case of validating the request JSON. However, I could not find any extractor for this. Thus I decided to write my own and share it with everyone. While I haven't put it in a crate, feel free to use the code as you wish.
An extractor allows us to pick apart the incoming request to get the parts our HTTP handler needs. More about extractors can be found here. There are two important traits when talking about extractors:
- FromRequestParts: This is used if the extractor does not need access to the request body.
- FromRequest: This is used if the extractor does need access to the request body. (we will be using this)
I will use validator crate for the actual validation.
Here is the code for our validated JSON extractor:
use ; use ; use Validate; ;
I am using
(StatusCode, &'static str) for error response since all the responses in my server are of this type. Feel free to use whatever you prefer.
It is important to note that extractors can use other extractors themselves. So we do not need to replicate the Json extractor.
As you can see, writing a custom extractor is relatively straightforward, especially when compared to writing a tower middleware.
Consider supporting me if you like my work.