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 RustApiConfig,
167 // Streaming responses
168 Sse,
169 SseEvent,
170 State,
171 StreamBody,
172 TracingLayer,
173 ValidatedJson,
174 WithStatus,
175 };
176
177 // Cookies extractor (feature-gated in core)
178 #[cfg(feature = "cookies")]
179 pub use rustapi_core::Cookies;
180
181 // Re-export the route! macro
182 pub use rustapi_core::route;
183
184 // Re-export validation - use validator derive macro directly
185 pub use validator::Validate;
186
187 // Re-export OpenAPI schema derive
188 pub use rustapi_openapi::{IntoParams, Schema};
189
190 // Re-export commonly used external types
191 pub use serde::{Deserialize, Serialize};
192 pub use tracing::{debug, error, info, trace, warn};
193
194 // JWT types (feature-gated)
195 #[cfg(feature = "jwt")]
196 pub use rustapi_extras::{
197 create_token, AuthUser, JwtError, JwtLayer, JwtValidation, ValidatedClaims,
198 };
199
200 // CORS types (feature-gated)
201 #[cfg(feature = "cors")]
202 pub use rustapi_extras::{AllowedOrigins, CorsLayer};
203
204 // Rate limiting types (feature-gated)
205 #[cfg(feature = "rate-limit")]
206 pub use rustapi_extras::RateLimitLayer;
207
208 // Configuration types (feature-gated)
209 #[cfg(feature = "config")]
210 pub use rustapi_extras::{
211 env_or, env_parse, load_dotenv, load_dotenv_from, require_env, Config, ConfigError,
212 Environment,
213 };
214
215 // SQLx types (feature-gated)
216 #[cfg(feature = "sqlx")]
217 pub use rustapi_extras::{convert_sqlx_error, SqlxErrorExt};
218
219 // TOON types (feature-gated)
220 #[cfg(feature = "toon")]
221 pub use rustapi_toon::{AcceptHeader, LlmResponse, Negotiate, OutputFormat, Toon};
222}
223
224#[cfg(test)]
225mod tests {
226 use super::prelude::*;
227
228 #[test]
229 fn prelude_imports_work() {
230 // This test ensures prelude exports compile correctly
231 let _: fn() -> Result<()> = || Ok(());
232 }
233}