Easy Guide to JSON Input Validation in Rust Web Services

Easy Guide to JSON Input Validation in Rust Web Services

JSON input validation is a core concern in any modern web application, and the Rust ecosystem already has some great tools for dealing with it. When building web services with somewhat complex domain objects, good input validation is paramount. Validation of user input is fundamentally important in terms of not just security — never trust external inputs — but also usability.

JSON input validation is a core concern in any modern web application, and the Rust ecosystem already has some great tools for dealing with it.

When building web services with somewhat complex domain objects, good input validation is paramount. Validation of user input is fundamentally important in terms of not just security — never trust external inputs — but also usability.

If the caller of a REST endpoint runs into an error, you want to be able to tell them what went wrong instead of simply displaying 400 Bad Request. Optimal input error handling is done in such a way that if you get invalid JSON, you can tell the user where, roughly, the error is located in the request payload.

If the request payload is valid JSON, the next step is to make sure it adheres to your specification. Rust, with the fantastic serde crate, helps here because deserialization to a struct will fail if a wrong data type is used. Again, if this happens, you need to tell the user that, for instance, name needs to be a String and not an Object, instead of simply replying JSON Parse Error.

But we’re still not quite done. Once the incoming JSON has been properly validated and parsed to a struct, our own validation starts — the validation based on our business logic. For example, you might want to validate that an email is actually an email according to a specification, or that a username does not contain forbidden characters, is a certain length, and so on. This part is easier to handle than the others, but it often results in many small, error-prone validation functions, which are hard to combine and distill into nice, clear error messages.

In this tutorial, we’ll explain how to solve these issues in Rust within a warp web service. Our solutions will be intuitive and user-friendly without compromising the maintainability of the code.

Let’s get started!

Setup

To follow along, all you need is a reasonably recent Rust installation (1.39+) and a tool to make HTTP requests, such as cURL.

First, create a new Rust project.

cargo new rust-json-validation-example
cd rust-json-validation-example

Next, edit the Cargo.toml file and add the dependencies you’ll need.

tokio = { version = "0.2", features = ["macros", "sync", "rt-threaded"] }
warp = "0.2"
serde = {version = "1.0", features = ["derive"] }
serde_json = "1.0"
validator = "0.10"
validator_derive = "0.10"
serde_path_to_error = "0.1"
thiserror = "1.0.20"
bytes = "0.5.6"

You’ll need warp and tokio for the web server and serde to deserialize the incoming body. The serde_path_to_error library will be your first stop to improve validation, and the validator and validator_derive crates will help later on with data validation.

JSON body validation

To demonstrate the default behavior in warp when sending something that’s invalid JSON or can’t be successfully deserialized, let’s create a small web server with a single route.

type Result<T> = std::result::Result<T, Rejection>;

#[derive(Deserialize, Debug)]
struct CreateRequest {
    pub email: String,
    pub address: Address,
    pub pets: Vec<Pet>,
}

#[derive(Deserialize, Debug)]
struct Address {
    pub street: String,
    pub street_no: usize,
}

#[derive(Deserialize, Serialize, Debug)]
struct Pet {
    pub name: String,
}

#[tokio::main]
async fn main() {
    let basic = warp::path!("create-basic")
        .and(warp::post())
        .and(warp::body::json())
        .and_then(create_handler);

    let routes = basic
        .recover(handle_rejection);

    println!("Server started at localhost:8080!");
    warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
}

async fn create_handler(body: CreateRequest) -> Result<impl Reply> {
    Ok(format!("called with: {:?}", body))
}

#[derive(Serialize)]
struct ErrorResponse {
    message: String,
    errors: Option<Vec<FieldError>>,
}

#[derive(Serialize)]
struct FieldError {
    field: String,
    field_errors: Vec<String>,
}

pub async fn handle_rejection(err: Rejection) -> std::result::Result<impl Reply, Infallible> {
    let (code, message, errors) = if err.is_not_found() {
        (StatusCode::NOT_FOUND, "Not Found".to_string(), None)
    } else if let Some(e) = err.find::<warp::filters::body::BodyDeserializeError>() {
        (
            StatusCode::BAD_REQUEST,
            e.source()
                .map(|cause| cause.to_string())
                .unwrap_or_else(|| "BAD_REQUEST".to_string()),
            None,
        )
    } else {
        eprintln!("unhandled error: {:?}", err);
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Internal Server Error".to_string(),
            None,
        )
    };

    let json = warp::reply::json(&ErrorResponse {
        message: message.into(),
        errors,
    });
    Ok(warp::reply::with_status(json, code))
}

With this, we created our request object — in this case just some fields we can have some fun validating, such as email, an address, and a list of Pets.

Then, we created a minimal handler, which takes this as a JSON body and, when called, prints it.

Below that, we defined some basic error handling within the handle_rejection helper. This is warp’s way of dealing with errors, which, in warp’s terminology, are called Rejections. You can ignore the FieldError for now; we’ll revisit it later on when we do data validation.

There is also a predefined case for errors happening during body deserialization: warp::filters::body::BodyDeserializeError. If we encounter an error like that, we return a 400 error with the cause of the error converted to a string.

Here’s how that looks from the caller’s side. Let’s send a wrong payload with cURL:

curl -X POST http://localhost:8080/create-basic -H "Content-Type: application/json" -d '{ "email": 1, "address": { "street": "warpstreet", "street_no": 1 }, "pets": [{ "name": "nacho" }] }'

We get the following error.

{"message":"invalid type: integer `1`, expected a string at line 1 column 13","errors":null}

It’s not too bad — at the very least, it tells us the line and column where the error was (email is a number in our wrong payload) — but it would be a lot nicer to have the error actually tell you that email was the problem.

In any case, this is much better than not having a BodyDeserializeError handler. iIn that case, the response would be:

{"message":"Internal Server Error","errors":null}

rust json web-development programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Software Developer vs Web Developer | Difference Web Developer & Software Developer

Software Developer vs Web Developer | Difference Web Developer & Software Developer | Software development and web development are normally used interchangeably. Although both include development, a software developer has different responsibilities from that of a web developer.

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.