2 stable releases
| 1.0.1 | Sep 30, 2025 |
|---|
#724 in HTTP server
248 downloads per month
220KB
4.5K
SLoC
🚀 Bytedocs - Rust
Production-ready Rust alternative to Swagger for API documentation with automatic route detection, AST parsing, and beautiful UI.
✨ Features
- 🤖 Automatic Route Detection - Automatically detects API routes from your source code using AST parsing
- 🎯 Deep Type Analysis - Extracts request/response types from function signatures like
Result<Json<PaginatedResponse<User>>, StatusCode> - 🎨 Beautiful UI - Clean, responsive interface with dark/light mode
- 🔐 Built-in Authentication - Session-based auth with IP banning and rate limiting
- 📊 OpenAPI 3.0.3 Compatible - Generates standard OpenAPI specifications
- 🔧 Framework Support - Works with Axum, Warp, Actix-web, and more
- ⚡ Production Ready - Comprehensive error handling, input validation, and security middleware
- 🚀 Zero Config - Works out of the box with sensible defaults
🚀 Quick Start
1. Add to Cargo.toml
[dependencies]
bytedocs-rs = "0.1.0"
axum = "0.7"
tokio = { version = "1.0", features = ["full"] }
2. Basic Usage
use bytedocs_rs::{build_docs_from_file, Config, create_docs_router};
use axum::Router;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
let config = Config {
title: "My API".to_string(),
description: "API documentation".to_string(),
version: "1.0.0".to_string(),
..Default::default()
};
let source = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("src")
.join("main.rs");
let docs = build_docs_from_file(config.clone(), source)
.expect("failed to analyse handlers");
let docs = Arc::new(Mutex::new(docs));
let docs_router = create_docs_router(docs, config.clone());
let app = Router::new().merge(docs_router);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
let service = app.into_make_service_with_connect_info::<SocketAddr>();
axum::serve(listener, service).await.unwrap();
}
3. View Documentation
Open your browser to http://localhost:3000/docs
🤖 AI Assistant Setup (Optional)
Bytedocs-rs includes an optional AI assistant for interactive API help.
Environment Variables
The AI configuration is handled in your application, not in the bytedocs package itself. For the example:
# In your project, load environment variables as needed
BYTEDOCS_AI_PROVIDER=demo
BYTEDOCS_AI_API_KEY=sk-your-api-key-here
BYTEDOCS_AI_MODEL=gpt-3.5-turbo
Supported AI Providers
- demo - Mock responses, no API key required
- openai - OpenAI GPT models (requires API key)
- gemini - Google Gemini (requires API key)
📖 Examples
Run the Example
git clone <repository>
cd bytedocs-rs
# Option 1: Demo mode (standalone example crate)
cd examples
cargo run
# Option 2: Run via Cargo example from the crate root
cargo run --example basic_example
The example loads AI configuration from .env. When running inside examples/, edit examples/.env and set your provider/API key before starting the server. The same file is also used when launching with cargo run --example basic_example from the crate root.
Bytedocs uses the incoming socket address for auth rate limiting, so make sure your Axum server is started with into_make_service_with_connect_info::<SocketAddr>() as shown in the snippet above.
When authentication is enabled, unauthenticated visitors will see the login prompt rendered directly at /docs.
Example Features
- 📋 User Management API - CRUD operations
- 📝 Blog Posts API - Content management
- 💚 Health Check - System monitoring
- 🤖 AI Chat - Interactive documentation assistant
Open http://localhost:3000/docs to explore the generated documentation.
🛠️ API Reference
Core Types
Config
pub struct Config {
pub title: String, // API title
pub description: String, // API description
pub version: String, // API version
pub base_url: Option<String>, // API base URL
pub docs_path: String, // Documentation path (default: "/docs")
pub ai_config: Option<AiConfig>, // AI assistant config
}
Adding Routes
docs.add_route("GET", "/users/{id}", "get_user")
.summary("Get user by ID")
.description("Retrieve a specific user")
.parameters(vec![
path_param("id", "integer", "User ID")
])
.build();
Parameter Helpers
use bytedocs_rs::{param, path_param};
// Query parameter
param("search", "string", "Search query", false)
// Path parameter
path_param("id", "integer", "Resource ID")
🎨 UI Features
- Interactive Documentation - Click to explore endpoints
- Search & Filter - Find endpoints quickly
- Dark/Light Theme - Automatic or manual toggle
- Mobile Responsive - Works on all devices
- Copy Examples - One-click code copying
- AI Chat - Get help understanding the API
🔧 Advanced Configuration
Custom UI Theme
ui_config: Some(UiConfig {
theme: "dark".to_string(),
show_try_it: true,
show_schemas: true,
title: Some("My Custom API Docs".to_string()),
..Default::default()
})
Multiple Base URLs
base_urls: Some(vec![
BaseUrlOption {
name: "Production".to_string(),
url: "https://api.example.com".to_string(),
},
BaseUrlOption {
name: "Staging".to_string(),
url: "https://staging-api.example.com".to_string(),
}
])
📊 Exports
OpenAPI JSON
Access the OpenAPI 3.0 specification at:
http://localhost:3000/docs/openapi.json
Raw API Data
Access the raw documentation data at:
http://localhost:3000/docs/api-data.json
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
Made with ❤️ in Rust 🦀
Dependencies
~21–39MB
~619K SLoC