A powerful Rust library for OpenAPI 3.1 specification parsing, validation, and request handling.
- OpenAPI 3.1 Support: Full compatibility with OpenAPI 3.1 specification
- YAML Parsing: Support for parsing OpenAPI documents from both YAML formats
- Request Validation: Comprehensive HTTP request validation including:
- Path parameter validation
- Query parameter validation
- Request body validation
- Type Safety: Strong typing support with union types and composite types
- Format Validation: Support for various data format validations (Email, UUID, DateTime, etc.)
- Multi-Framework Integration: Built-in integration support for multiple web frameworks
- Observability: Built-in logging and metrics for validation operations with structured logs
- Detailed Error Messages: Clear and informative validation error messages
Add this to your Cargo.toml
:
[dependencies]
openapi-rs = { git = "https://github.com/baerwang/openapi-rs", features = ["axum"] }
axum = "0.7"
use openapi_rs::model::parse::OpenAPI;
use openapi_rs::request::axum::RequestData;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Parse OpenAPI specification from YAML file
// You can use the example file included in the project: examples/api.yaml
let content = std::fs::read_to_string("examples/api.yaml")?;
let openapi = OpenAPI::yaml(&content)?;
// Create request data for validation
let request_data = RequestData {
path: "/users".to_string(),
inner: axum::http::Request::builder()
.method("GET")
.uri("/users?page=1&limit=10")
.body(axum::body::Body::empty())
.unwrap(),
body: None,
};
// Validate the request against OpenAPI specification
openapi.validator(request_data)?;
// For POST requests with body
let body_data = r#"{"name": "John Doe", "email": "[email protected]", "age": 30}"#;
let post_request = RequestData {
path: "/users".to_string(),
inner: axum::http::Request::builder()
.method("POST")
.uri("/users")
.header("content-type", "application/json")
.body(axum::body::Body::from(body_data))
.unwrap(),
body: Some(axum::body::Bytes::from(body_data)),
};
openapi.validator(post_request)?;
Ok(())
}
Example OpenAPI Specification File (examples/api.yaml
):
This library includes a complete example OpenAPI specification file that demonstrates a User Management API definition, featuring:
- 📝 User CRUD Operations: Create, Read, Update, Delete users
- 🔍 Query Parameter Validation: Pagination, search parameters
- 📋 Request Body Validation: JSON formatted user data
- 🏷️ Data Type Validation: Strings, numbers, booleans, arrays
- 📧 Format Validation: Email, UUID, date-time formats
- String: Length constraints and format validation
- Number: Minimum and maximum value validation
- Integer: Range validation
- Boolean: Type validation
- Array: Item count constraints
- Object: Nested property validation
- Union Types: Multi-type validation
- Email (
email
) - UUID (
uuid
) - Date (
date
) - Time (
time
) - Date-Time (
date-time
) - IPv4 Address (
ipv4
) - IPv6 Address (
ipv6
) - Base64 Encoding (
base64
) - Binary Data (
binary
)
- String length (
minLength
,maxLength
) - Numeric ranges (
minimum
,maximum
) - Array item count (
minItems
,maxItems
) - Required fields (
required
) - Enum values (
enum
) - Pattern matching (
pattern
)
This library provides built-in observability features to help monitor and debug validation operations in production environments.
- Structured Logging: Automatic logging of validation operations with detailed metrics
- Performance Tracking: Duration measurement for each validation request
- Error Reporting: Detailed error logging for failed validations
- Request Context: Method and path tracking for comprehensive monitoring
The observability system generates structured logs with the following information:
Successful Validation:
INFO openapi_validation method="GET" path="/example/{uuid}" success=true duration_ms=2 timestamp=1642752000000
Failed Validation:
WARN openapi_validation method="GET" path="/example/{uuid}" success=false duration_ms=1 error="Invalid UUID format" timestamp=1642752000001
You can run the included observability example to see the logging in action:
RUST_LOG=debug cargo run --example observability_test
For detailed implementation, see: observability_test.rs
Run tests:
cargo test
- Parser: OpenAPI 3.1 specification parsing
- Validator: Complete request validation functionality
- More Framework Integration: Support for Actix-web、Axum, and other frameworks
- Performance Optimization: Improve handling of large API specifications
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.