#actix-web #validation #web-request #web-apps #error #interface #automatic

actix-web-validation

A common validation interface for actix-web applications

9 releases (5 breaking)

new 0.6.0 Nov 17, 2024
0.5.1 Aug 22, 2024
0.4.1 Aug 10, 2024
0.3.0 Jul 13, 2024
0.1.1 Jul 6, 2024

#272 in HTTP server

Download history 111/week @ 2024-07-28 133/week @ 2024-08-04 363/week @ 2024-08-11 300/week @ 2024-08-18 99/week @ 2024-08-25 70/week @ 2024-09-01 4/week @ 2024-09-08 1/week @ 2024-09-15 21/week @ 2024-09-22 38/week @ 2024-09-29 2/week @ 2024-10-06 57/week @ 2024-10-13 12/week @ 2024-10-20 16/week @ 2024-10-27 49/week @ 2024-11-03 25/week @ 2024-11-10

113 downloads per month

MIT license

41KB
819 lines

Actix Web Validation

tests crates.io docs.rs MSRV

Request validation for actix-web.

Supported Validation Libraries

Usage

Any type that implements the Actix FromRequest trait can be automatically validated.

# Cargo.toml
actix-web-validation = { version = "0.0.0", features = ["validator"] }
# or 
actix-web-validation = { version = "0.0.0", features = ["garde"] }
# or 
actix-web-validation = { version = "0.0.0", features = ["custom"] }
use actix_web_validation::Validated;

// Do validation using your validation library
#[derive(Debug, Validate, Deserialize)]
struct Example {
    #[validate(length(min = 3))]
    name: String,
}

// Wrap your Actix extractor with `Validated` to automatically run validation
#[post("/")]
async fn hello(Validated(Json(payload)): Validated<Json<Example>>) -> impl Responder {
    HttpResponse::Ok().body(format!("Hello {}", payload.name))
}

Custom Errors

Custom error responses can achieved by providing an error handler.

Below is an example custom error response that responds with JSON

#[derive(Debug, Serialize, Error)]
struct CustomErrorResponse {
    custom_message: String,
    errors: Vec<String>,
}

impl ResponseError for CustomErrorResponse {
    fn status_code(&self) -> actix_web::http::StatusCode {
        actix_web::http::StatusCode::BAD_REQUEST
    }

    fn error_response(&self) -> HttpResponse<actix_web::body::BoxBody> {
        HttpResponse::build(self.status_code()).body(serde_json::to_string(self).unwrap())
    }
}

Below is an example for the validator crate

fn error_handler(errors: ::validator::ValidationErrors, req: &HttpRequest) -> actix_web::Error {
    CustomErrorResponse {
        custom_message: "My custom message".to_string(),
        errors: errors
            .errors()
            .iter()
            .map(|(err, _)| err.to_string())
            .collect(),
    }
    .into()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .validator_error_handler(Arc::new(error_handler))
            // ....
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Below is an example for the garde crate

fn error_handler(errors: ::garde::Report, req: &HttpRequest) -> actix_web::Error {
    CustomErrorResponse {
        custom_message: "My custom message".to_string(),
        errors: errors.iter().map(|(_, err)| err.to_string()).collect(),
    }
    .into()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .garde_error_handler(Arc::new(error_handler))
            // ....
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Motivations

This library is heavily inspired by Spring Validation and actix-web-validator.

The actix-web-validator is great but there are a few pain points I would like to address with this library.

  • More explicit validation by using the Validated extractor to reduce the risk of using the wrong Json/Query/etc extractor by mistake.
  • Provide a common interface for validation libraries that can be extended as the Rust ecosystem evolves.

Limitations

Due to how Rust handles overlapping trait implementations, the actix_web_validation::Validated can only be used when 1 feature flag is enabled. This probably won't impact most use cases because most applications will just use 1 validation library for everything. If you need to use multiple validation libraries at the same time, this library can still be used but, you will need to fully qualify the import like actix_web_validation::validator::Validated, actix_web_validation::garde::Validated, and actix_web_validation::custom::Validated.

Dependencies

~15–27MB
~447K SLoC