# OpenAPI-RS
---
A powerful Rust library for OpenAPI 3.1 specification parsing, validation, and request handling.
### π Features
- **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
- [**Axum**](examples/axum): Complete Axum framework integration
- [**Actix-Web**](examples/actix-web): Complete Actix-Web framework integration
- **Optional Features**: Support for enabling specific frameworks on demand
- **Observability**: Built-in logging and metrics for validation operations with structured logs
- **Detailed Error Messages**: Clear and informative validation error messages
### π¦ Installation
Add this to your `Cargo.toml`:
```toml
[dependencies]
openapi-rs = { git = "https://github.com/baerwang/openapi-rs", features = ["axum"] }
axum = "0.7"
```
### π§ Usage
```rust
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": "john.doe@example.com", "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
### π― Supported Validation Types
#### Data Types
- **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
#### Format 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`)
#### Validation Constraints
- String length (`minLength`, `maxLength`)
- Numeric ranges (`minimum`, `maximum`)
- Array item count (`minItems`, `maxItems`)
- Required fields (`required`)
- Enum values (`enum`)
- Pattern matching (`pattern`)
### π Observability
This library provides built-in observability features to help monitor and debug validation operations in production
environments.
#### Features
- **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
#### Log Output Format
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
```
#### Running the Observability Example
You can run the included observability example to see the logging in action:
```bash
RUST_LOG=debug cargo run --example observability_test
```
For detailed implementation, see: [observability_test.rs](examples/observability_test.rs)
### π§ͺ Testing
Run tests:
```bash
cargo test
```
### π Roadmap
- [x] **Parser**: OpenAPI 3.1 specification parsing
- [x] **Validator**: Complete request validation functionality
- [x] **More Framework Integration**: Support for Actix-webγAxum, and other frameworks
- [x] **Performance Optimization**: Improve handling of large API specifications
### π€ Contributing
Contributions are welcome! Please follow these steps:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
### π License
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.