rustapi_rs/
lib.rs

1//! # RustAPI
2//!
3//! A FastAPI-like web framework for Rust.
4//!
5//! RustAPI combines Rust's performance and safety with FastAPI's "just write business logic"
6//! approach. It provides automatic OpenAPI documentation, declarative validation, and
7//! a developer-friendly experience.
8//!
9//! ## Quick Start
10//!
11//! ```rust,ignore
12//! use rustapi_rs::prelude::*;
13//!
14//! #[derive(Serialize, Schema)]
15//! struct Hello {
16//!     message: String,
17//! }
18//!
19//! async fn hello() -> Json<Hello> {
20//!     Json(Hello {
21//!         message: "Hello, World!".to_string(),
22//!     })
23//! }
24//!
25//! #[tokio::main]
26//! async fn main() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync>> {
27//!     RustApi::new()
28//!         .route("/", get(hello))
29//!         .run("127.0.0.1:8080")
30//!         .await
31//! }
32//! ```
33//!
34//! ## Features
35//!
36//! - **DX-First**: Minimal boilerplate, intuitive API
37//! - **Type-Safe**: Compile-time route and schema validation
38//! - **Auto Documentation**: OpenAPI + Swagger UI out of the box
39//! - **Declarative Validation**: Pydantic-style validation on structs
40//! - **Batteries Included**: JWT, CORS, rate limiting (optional features)
41//!
42//! ## Optional Features
43//!
44//! Enable these features in your `Cargo.toml`:
45//!
46//! - `jwt` - JWT authentication middleware and `AuthUser<T>` extractor
47//! - `cors` - CORS middleware with builder pattern configuration
48//! - `rate-limit` - IP-based rate limiting middleware
49//! - `config` - Configuration management with `.env` file support
50//! - `cookies` - Cookie parsing extractor
51//! - `sqlx` - SQLx database error conversion to ApiError
52//! - `extras` - Meta feature enabling jwt, cors, and rate-limit
53//! - `full` - All optional features enabled
54//!
55//! ```toml
56//! [dependencies]
57//! rustapi-rs = { version = "0.1", features = ["jwt", "cors"] }
58//! ```
59
60// Re-export core functionality
61pub use rustapi_core::*;
62
63// Re-export macros
64pub use rustapi_macros::*;
65
66// Re-export extras (feature-gated)
67#[cfg(feature = "jwt")]
68pub use rustapi_extras::jwt;
69#[cfg(feature = "jwt")]
70pub use rustapi_extras::{
71    create_token, AuthUser, JwtError, JwtLayer, JwtValidation, ValidatedClaims,
72};
73
74#[cfg(feature = "cors")]
75pub use rustapi_extras::cors;
76#[cfg(feature = "cors")]
77pub use rustapi_extras::{AllowedOrigins, CorsLayer};
78
79#[cfg(feature = "rate-limit")]
80pub use rustapi_extras::rate_limit;
81#[cfg(feature = "rate-limit")]
82pub use rustapi_extras::RateLimitLayer;
83
84#[cfg(feature = "config")]
85pub use rustapi_extras::config;
86#[cfg(feature = "config")]
87pub use rustapi_extras::{
88    env_or, env_parse, load_dotenv, load_dotenv_from, require_env, Config, ConfigError, Environment,
89};
90
91#[cfg(feature = "sqlx")]
92pub use rustapi_extras::sqlx;
93#[cfg(feature = "sqlx")]
94pub use rustapi_extras::{convert_sqlx_error, SqlxErrorExt};
95
96// Re-export TOON (feature-gated)
97#[cfg(feature = "toon")]
98pub mod toon {
99    //! TOON (Token-Oriented Object Notation) support
100    //!
101    //! TOON is a compact format for LLM communication that reduces token usage by 20-40%.
102    //!
103    //! # Example
104    //!
105    //! ```rust,ignore
106    //! use rustapi_rs::toon::{Toon, Negotiate, AcceptHeader};
107    //!
108    //! // As extractor
109    //! async fn handler(Toon(data): Toon<MyType>) -> impl IntoResponse { ... }
110    //!
111    //! // As response
112    //! async fn handler() -> Toon<MyType> { Toon(my_data) }
113    //!
114    //! // Content negotiation (returns JSON or TOON based on Accept header)
115    //! async fn handler(accept: AcceptHeader) -> Negotiate<MyType> {
116    //!     Negotiate::new(my_data, accept.preferred)
117    //! }
118    //! ```
119    pub use rustapi_toon::*;
120}
121
122/// Prelude module - import everything you need with `use rustapi_rs::prelude::*`
123pub mod prelude {
124    // Core types
125    pub use rustapi_core::{
126        delete,
127        delete_route,
128        get,
129        get_route,
130        patch,
131        patch_route,
132        post,
133        post_route,
134        put,
135        put_route,
136        // Error handling
137        ApiError,
138        Body,
139        ClientIp,
140        Created,
141        Extension,
142        HeaderValue,
143        Headers,
144        Html,
145        // Response types
146        IntoResponse,
147        // Extractors
148        Json,
149        NoContent,
150        Path,
151        Query,
152        Redirect,
153        // Request context
154        Request,
155        // Middleware
156        RequestId,
157        RequestIdLayer,
158        Response,
159        Result,
160        // Route type for macro-based routing
161        Route,
162        // Router
163        Router,
164        // App builder
165        RustApi,
166        // Streaming responses
167        Sse,
168        SseEvent,
169        State,
170        StreamBody,
171        TracingLayer,
172        ValidatedJson,
173        WithStatus,
174    };
175
176    // Cookies extractor (feature-gated in core)
177    #[cfg(feature = "cookies")]
178    pub use rustapi_core::Cookies;
179
180    // Re-export the route! macro
181    pub use rustapi_core::route;
182
183    // Re-export validation - use validator derive macro directly
184    pub use validator::Validate;
185
186    // Re-export OpenAPI schema derive
187    pub use rustapi_openapi::{IntoParams, Schema};
188
189    // Re-export commonly used external types
190    pub use serde::{Deserialize, Serialize};
191    pub use tracing::{debug, error, info, trace, warn};
192
193    // JWT types (feature-gated)
194    #[cfg(feature = "jwt")]
195    pub use rustapi_extras::{
196        create_token, AuthUser, JwtError, JwtLayer, JwtValidation, ValidatedClaims,
197    };
198
199    // CORS types (feature-gated)
200    #[cfg(feature = "cors")]
201    pub use rustapi_extras::{AllowedOrigins, CorsLayer};
202
203    // Rate limiting types (feature-gated)
204    #[cfg(feature = "rate-limit")]
205    pub use rustapi_extras::RateLimitLayer;
206
207    // Configuration types (feature-gated)
208    #[cfg(feature = "config")]
209    pub use rustapi_extras::{
210        env_or, env_parse, load_dotenv, load_dotenv_from, require_env, Config, ConfigError,
211        Environment,
212    };
213
214    // SQLx types (feature-gated)
215    #[cfg(feature = "sqlx")]
216    pub use rustapi_extras::{convert_sqlx_error, SqlxErrorExt};
217
218    // TOON types (feature-gated)
219    #[cfg(feature = "toon")]
220    pub use rustapi_toon::{AcceptHeader, LlmResponse, Negotiate, OutputFormat, Toon};
221}
222
223#[cfg(test)]
224mod tests {
225    use super::prelude::*;
226
227    #[test]
228    fn prelude_imports_work() {
229        // This test ensures prelude exports compile correctly
230        let _: fn() -> Result<()> = || Ok(());
231    }
232}