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::{convert_sqlx_error, SqlxErrorExt};
93
94// Re-export Phase 11 & Observability Features
95#[cfg(feature = "timeout")]
96pub use rustapi_extras::timeout;
97
98#[cfg(feature = "guard")]
99pub use rustapi_extras::guard;
100
101#[cfg(feature = "logging")]
102pub use rustapi_extras::logging;
103
104#[cfg(feature = "circuit-breaker")]
105pub use rustapi_extras::circuit_breaker;
106
107#[cfg(feature = "retry")]
108pub use rustapi_extras::retry;
109
110#[cfg(feature = "security-headers")]
111pub use rustapi_extras::security_headers;
112
113#[cfg(feature = "api-key")]
114pub use rustapi_extras::api_key;
115
116#[cfg(feature = "cache")]
117pub use rustapi_extras::cache;
118
119#[cfg(feature = "dedup")]
120pub use rustapi_extras::dedup;
121
122#[cfg(feature = "sanitization")]
123pub use rustapi_extras::sanitization;
124
125#[cfg(feature = "otel")]
126pub use rustapi_extras::otel;
127
128#[cfg(feature = "structured-logging")]
129pub use rustapi_extras::structured_logging;
130
131// Re-export TOON (feature-gated)
132#[cfg(feature = "toon")]
133pub mod toon {
134 //! TOON (Token-Oriented Object Notation) support
135 //!
136 //! TOON is a compact format for LLM communication that reduces token usage by 20-40%.
137 //!
138 //! # Example
139 //!
140 //! ```rust,ignore
141 //! use rustapi_rs::toon::{Toon, Negotiate, AcceptHeader};
142 //!
143 //! // As extractor
144 //! async fn handler(Toon(data): Toon<MyType>) -> impl IntoResponse { ... }
145 //!
146 //! // As response
147 //! async fn handler() -> Toon<MyType> { Toon(my_data) }
148 //!
149 //! // Content negotiation (returns JSON or TOON based on Accept header)
150 //! async fn handler(accept: AcceptHeader) -> Negotiate<MyType> {
151 //! Negotiate::new(my_data, accept.preferred)
152 //! }
153 //! ```
154 pub use rustapi_toon::*;
155}
156
157// Re-export WebSocket support (feature-gated)
158#[cfg(feature = "ws")]
159pub mod ws {
160 //! WebSocket support for real-time bidirectional communication
161 //!
162 //! This module provides WebSocket functionality through the `WebSocket` extractor,
163 //! enabling real-time communication patterns like chat, live updates, and streaming.
164 //!
165 //! # Example
166 //!
167 //! ```rust,ignore
168 //! use rustapi_rs::ws::{WebSocket, Message};
169 //!
170 //! async fn websocket_handler(ws: WebSocket) -> impl IntoResponse {
171 //! ws.on_upgrade(|mut socket| async move {
172 //! while let Some(Ok(msg)) = socket.recv().await {
173 //! if let Message::Text(text) = msg {
174 //! socket.send(Message::Text(format!("Echo: {}", text))).await.ok();
175 //! }
176 //! }
177 //! })
178 //! }
179 //! ```
180 pub use rustapi_ws::*;
181}
182
183// Re-export View/Template support (feature-gated)
184#[cfg(feature = "view")]
185pub mod view {
186 //! Template engine support for server-side rendering
187 //!
188 //! This module provides Tera-based templating with the `View<T>` response type,
189 //! enabling server-side HTML rendering with template inheritance and context.
190 //!
191 //! # Example
192 //!
193 //! ```rust,ignore
194 //! use rustapi_rs::view::{Templates, View, ContextBuilder};
195 //!
196 //! #[derive(Clone)]
197 //! struct AppState {
198 //! templates: Templates,
199 //! }
200 //!
201 //! async fn index(State(state): State<AppState>) -> View<()> {
202 //! View::new(&state.templates, "index.html")
203 //! .with("title", "Home")
204 //! .with("message", "Welcome!")
205 //! }
206 //! ```
207 pub use rustapi_view::*;
208}
209
210/// Prelude module - import everything you need with `use rustapi_rs::prelude::*`
211pub mod prelude {
212 // Core types
213 pub use rustapi_core::{
214 delete,
215 delete_route,
216 get,
217 get_route,
218 patch,
219 patch_route,
220 post,
221 post_route,
222 put,
223 put_route,
224 serve_dir,
225 sse_response,
226 // Error handling
227 ApiError,
228 Body,
229 ClientIp,
230 Created,
231 Extension,
232 HeaderValue,
233 Headers,
234 Html,
235 // Response types
236 IntoResponse,
237 // Extractors
238 Json,
239 KeepAlive,
240 // Multipart
241 Multipart,
242 MultipartConfig,
243 MultipartField,
244 NoContent,
245 Path,
246 Query,
247 Redirect,
248 // Request context
249 Request,
250 // Middleware
251 RequestId,
252 RequestIdLayer,
253 Response,
254 Result,
255 // Route type for macro-based routing
256 Route,
257 // Router
258 Router,
259 // App builder
260 RustApi,
261 RustApiConfig,
262 // Streaming responses
263 Sse,
264 SseEvent,
265 State,
266 // Static files
267 StaticFile,
268 StaticFileConfig,
269 StreamBody,
270 TracingLayer,
271 UploadedFile,
272 ValidatedJson,
273 WithStatus,
274 };
275
276 // Compression middleware (feature-gated in core)
277 #[cfg(feature = "compression")]
278 pub use rustapi_core::middleware::{CompressionAlgorithm, CompressionConfig};
279 #[cfg(feature = "compression")]
280 pub use rustapi_core::CompressionLayer;
281
282 // Cookies extractor (feature-gated in core)
283 #[cfg(feature = "cookies")]
284 pub use rustapi_core::Cookies;
285
286 // Re-export the route! macro
287 pub use rustapi_core::route;
288
289 // Re-export validation - use validator derive macro directly
290 pub use validator::Validate;
291
292 // Re-export OpenAPI schema derive
293 pub use rustapi_openapi::{IntoParams, Schema};
294
295 // Re-export commonly used external types
296 pub use serde::{Deserialize, Serialize};
297 pub use tracing::{debug, error, info, trace, warn};
298
299 // JWT types (feature-gated)
300 #[cfg(feature = "jwt")]
301 pub use rustapi_extras::{
302 create_token, AuthUser, JwtError, JwtLayer, JwtValidation, ValidatedClaims,
303 };
304
305 // CORS types (feature-gated)
306 #[cfg(feature = "cors")]
307 pub use rustapi_extras::{AllowedOrigins, CorsLayer};
308
309 // Rate limiting types (feature-gated)
310 #[cfg(feature = "rate-limit")]
311 pub use rustapi_extras::RateLimitLayer;
312
313 // Configuration types (feature-gated)
314 #[cfg(feature = "config")]
315 pub use rustapi_extras::{
316 env_or, env_parse, load_dotenv, load_dotenv_from, require_env, Config, ConfigError,
317 Environment,
318 };
319
320 // SQLx types (feature-gated)
321 #[cfg(feature = "sqlx")]
322 pub use rustapi_extras::{convert_sqlx_error, SqlxErrorExt};
323
324 // TOON types (feature-gated)
325 #[cfg(feature = "toon")]
326 pub use rustapi_toon::{AcceptHeader, LlmResponse, Negotiate, OutputFormat, Toon};
327
328 // WebSocket types (feature-gated)
329 #[cfg(feature = "ws")]
330 pub use rustapi_ws::{Broadcast, Message, WebSocket, WebSocketStream};
331
332 // View/Template types (feature-gated)
333 #[cfg(feature = "view")]
334 pub use rustapi_view::{ContextBuilder, Templates, TemplatesConfig, View};
335}
336
337#[cfg(test)]
338mod tests {
339 use super::prelude::*;
340
341 #[test]
342 fn prelude_imports_work() {
343 // This test ensures prelude exports compile correctly
344 let _: fn() -> Result<()> = || Ok(());
345 }
346}