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,no_run
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::validation::Validatable;
214 pub use rustapi_core::{
215 delete,
216 delete_route,
217 get,
218 get_route,
219 patch,
220 patch_route,
221 post,
222 post_route,
223 put,
224 put_route,
225 serve_dir,
226 sse_response,
227 // Error handling
228 ApiError,
229 AsyncValidatedJson,
230 Body,
231 ClientIp,
232 Created,
233 Extension,
234 HeaderValue,
235 Headers,
236 Html,
237 // Response types
238 IntoResponse,
239 // Extractors
240 Json,
241 KeepAlive,
242 // Multipart
243 Multipart,
244 MultipartConfig,
245 MultipartField,
246 NoContent,
247 Path,
248 Query,
249 Redirect,
250 // Request context
251 Request,
252 // Middleware
253 RequestId,
254 RequestIdLayer,
255 Response,
256 Result,
257 // Route type for macro-based routing
258 Route,
259 // Router
260 Router,
261 // App builder
262 RustApi,
263 RustApiConfig,
264 // Streaming responses
265 Sse,
266 SseEvent,
267 State,
268 // Static files
269 StaticFile,
270 StaticFileConfig,
271 StatusCode,
272 StreamBody,
273 TracingLayer,
274 Typed,
275 TypedPath,
276 UploadedFile,
277 ValidatedJson,
278 WithStatus,
279 };
280
281 // Compression middleware (feature-gated in core)
282 #[cfg(feature = "compression")]
283 pub use rustapi_core::middleware::{CompressionAlgorithm, CompressionConfig};
284 #[cfg(feature = "compression")]
285 pub use rustapi_core::CompressionLayer;
286
287 // Cookies extractor (feature-gated in core)
288 #[cfg(feature = "cookies")]
289 pub use rustapi_core::Cookies;
290
291 // Re-export the route! macro
292 pub use rustapi_core::route;
293
294 // Re-export TypedPath derive macro
295 pub use rustapi_macros::ApiError;
296 pub use rustapi_macros::TypedPath;
297
298 // Re-export validation - use validator derive macro directly
299 pub use rustapi_validate::v2::AsyncValidate;
300 pub use rustapi_validate::v2::Validate as V2Validate;
301 pub use validator::Validate;
302
303 // Re-export OpenAPI schema derive
304 pub use rustapi_openapi::{IntoParams, Schema};
305
306 // Re-export commonly used external types
307 pub use serde::{Deserialize, Serialize};
308 pub use tracing::{debug, error, info, trace, warn};
309
310 // JWT types (feature-gated)
311 #[cfg(feature = "jwt")]
312 pub use rustapi_extras::{
313 create_token, AuthUser, JwtError, JwtLayer, JwtValidation, ValidatedClaims,
314 };
315
316 // CORS types (feature-gated)
317 #[cfg(feature = "cors")]
318 pub use rustapi_extras::{AllowedOrigins, CorsLayer};
319
320 // Rate limiting types (feature-gated)
321 #[cfg(feature = "rate-limit")]
322 pub use rustapi_extras::RateLimitLayer;
323
324 // Configuration types (feature-gated)
325 #[cfg(feature = "config")]
326 pub use rustapi_extras::{
327 env_or, env_parse, load_dotenv, load_dotenv_from, require_env, Config, ConfigError,
328 Environment,
329 };
330
331 // SQLx types (feature-gated)
332 #[cfg(feature = "sqlx")]
333 pub use rustapi_extras::{convert_sqlx_error, SqlxErrorExt};
334
335 // TOON types (feature-gated)
336 #[cfg(feature = "toon")]
337 pub use rustapi_toon::{AcceptHeader, LlmResponse, Negotiate, OutputFormat, Toon};
338
339 // WebSocket types (feature-gated)
340 #[cfg(feature = "ws")]
341 pub use rustapi_ws::{Broadcast, Message, WebSocket, WebSocketStream};
342
343 // View/Template types (feature-gated)
344 #[cfg(feature = "view")]
345 pub use rustapi_view::{ContextBuilder, Templates, TemplatesConfig, View};
346}
347
348#[cfg(test)]
349mod tests {
350 use super::prelude::*;
351
352 #[test]
353 fn prelude_imports_work() {
354 // This test ensures prelude exports compile correctly
355 let _: fn() -> Result<()> = || Ok(());
356 }
357}