Skip to content

Commit 13c866e

Browse files
committed
Merge dev into main
2 parents 4f450e9 + 41f8fb6 commit 13c866e

38 files changed

Lines changed: 7172 additions & 188 deletions

README.md

Lines changed: 351 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,352 @@
11
# OSBot-Fast-API
2-
OSBot helpers for FastAPI..
2+
3+
![Current Release](https://img.shields.io/badge/release-v0.10.5-blue)
4+
![Python](https://img.shields.io/badge/python-3.8+-green)
5+
![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-red)
6+
![Type-Safe](https://img.shields.io/badge/Type--Safe-✓-brightgreen)
7+
![AWS Lambda](https://img.shields.io/badge/AWS_Lambda-Ready-orange)
8+
9+
A Type-Safe wrapper around FastAPI that provides strong typing, comprehensive middleware support, HTTP event tracking, and seamless AWS Lambda integration through Mangum.
10+
11+
## ✨ Key Features
12+
13+
- **🔐 Type-Safe First**: Automatic bidirectional conversion between Type_Safe classes and Pydantic BaseModels
14+
- **🛡️ Built-in Middleware**: API key validation, CORS, disconnect detection, and HTTP event tracking
15+
- **📊 HTTP Event System**: Comprehensive request/response tracking with configurable storage
16+
- **🚀 AWS Lambda Ready**: Direct integration with Mangum for serverless deployment
17+
- **🧪 Testing Utilities**: Built-in test server with Type-Safe support
18+
- **🔄 Auto-conversion**: Seamless Type_Safe ↔ BaseModel ↔ Dataclass conversions
19+
- **📝 Route Organization**: Clean route structure with automatic path generation
20+
21+
## 📦 Installation
22+
23+
```bash
24+
pip install osbot-fast-api
25+
```
26+
27+
## 🚀 Quick Start
28+
29+
### Basic Application
30+
31+
```python
32+
from osbot_fast_api.api.Fast_API import Fast_API
33+
from osbot_fast_api.api.Fast_API_Routes import Fast_API_Routes
34+
from osbot_utils.type_safe.Type_Safe import Type_Safe
35+
36+
# Define Type-Safe schema
37+
class User(Type_Safe):
38+
username: str
39+
email: str
40+
age: int
41+
42+
# Create routes
43+
class Routes_Users(Fast_API_Routes):
44+
tag = 'users'
45+
46+
def create_user(self, user: User):
47+
# user is automatically converted from BaseModel to Type_Safe
48+
return {'created': user.username}
49+
50+
def get_user__id(self, id: str): # Becomes /users/get-user/{id}
51+
return {'user_id': id}
52+
53+
def setup_routes(self):
54+
self.add_route_post(self.create_user)
55+
self.add_route_get(self.get_user__id)
56+
57+
# Setup application
58+
fast_api = Fast_API(enable_cors=True)
59+
fast_api.setup()
60+
fast_api.add_routes(Routes_Users)
61+
62+
# Get FastAPI app instance
63+
app = fast_api.app()
64+
```
65+
66+
### With Middleware & Authentication
67+
68+
```python
69+
import os
70+
71+
# Configure API key authentication
72+
os.environ['FAST_API__AUTH__API_KEY__NAME'] = 'X-API-Key'
73+
os.environ['FAST_API__AUTH__API_KEY__VALUE'] = 'your-secret-key'
74+
75+
# Create app with middleware
76+
fast_api = Fast_API(
77+
enable_cors=True, # Enable CORS support
78+
enable_api_key=True, # Enable API key validation
79+
default_routes=True # Add /status, /version routes
80+
)
81+
82+
# Configure HTTP event tracking
83+
fast_api.http_events.max_requests_logged = 100
84+
fast_api.http_events.clean_data = True # Sanitize sensitive headers
85+
86+
fast_api.setup()
87+
```
88+
89+
## 🏗️ Architecture
90+
91+
OSBot-Fast-API extends FastAPI with a comprehensive Type-Safe layer and monitoring capabilities:
92+
93+
```
94+
┌─────────────────────────────────────────────────────┐
95+
│ Your Application │
96+
│ │
97+
│ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │
98+
│ │ Type-Safe │ │ Routes │ │ Events │ │
99+
│ │ Schemas │ │ Classes │ │ Handlers │ │
100+
│ └──────────────┘ └──────────────┘ └──────────┘ │
101+
└───────────────────────┬─────────────────────────────┘
102+
103+
┌───────────────────────▼─────────────────────────────┐
104+
│ OSBot-Fast-API │
105+
│ │
106+
│ ┌────────────────────────────────────────────┐ │
107+
│ │ Type Conversion System │ │
108+
│ │ Type_Safe ↔ BaseModel ↔ Dataclass │ │
109+
│ └────────────────────────────────────────────┘ │
110+
│ │
111+
│ ┌────────────────────────────────────────────┐ │
112+
│ │ Middleware Pipeline │ │
113+
│ │ Disconnect → Events → CORS → API Key │ │
114+
│ └────────────────────────────────────────────┘ │
115+
│ │
116+
│ ┌────────────────────────────────────────────┐ │
117+
│ │ HTTP Event Tracking System │ │
118+
│ │ Request/Response/Traces/Monitoring │ │
119+
│ └────────────────────────────────────────────┘ │
120+
└───────────────────────┬─────────────────────────────┘
121+
122+
┌───────────────────────▼─────────────────────────────┐
123+
│ FastAPI │
124+
└─────────────────────────────────────────────────────┘
125+
```
126+
127+
## 🔐 Type-Safe Integration
128+
129+
OSBot-Fast-API automatically converts between Type_Safe classes and Pydantic BaseModels:
130+
131+
```python
132+
from osbot_utils.type_safe.Type_Safe import Type_Safe
133+
from typing import List, Optional
134+
135+
# Define Type-Safe schemas (not Pydantic!)
136+
class Address(Type_Safe):
137+
street: str
138+
city: str
139+
country: str
140+
141+
class Person(Type_Safe):
142+
name: str
143+
age: int
144+
email: Optional[str] = None
145+
addresses: List[Address] = []
146+
147+
# Use directly in routes - automatic conversion happens
148+
class Routes_People(Fast_API_Routes):
149+
tag = 'people'
150+
151+
def create_person(self, person: Person):
152+
# person is Type_Safe instance, not BaseModel
153+
# Full type validation and conversion handled automatically
154+
return person # Automatically converted back to JSON
155+
156+
def setup_routes(self):
157+
self.add_route_post(self.create_person)
158+
```
159+
160+
## 📊 HTTP Event Tracking
161+
162+
Built-in comprehensive request/response tracking:
163+
164+
```python
165+
# Configure event tracking
166+
fast_api.http_events.max_requests_logged = 100
167+
fast_api.http_events.clean_data = True # Sanitize sensitive data
168+
fast_api.http_events.trace_calls = True # Enable execution tracing (debug)
169+
170+
# Add event callbacks
171+
def on_request(event):
172+
print(f"Request: {event.http_event_request.path}")
173+
174+
def on_response(response, event):
175+
print(f"Response: {event.http_event_response.status_code}")
176+
print(f"Duration: {event.http_event_request.duration}s")
177+
178+
fast_api.http_events.callback_on_request = on_request
179+
fast_api.http_events.callback_on_response = on_response
180+
```
181+
182+
## 🛡️ Middleware Stack
183+
184+
Built-in middleware pipeline (in execution order):
185+
186+
1. **Detect_Disconnect**: Monitor client disconnections
187+
2. **Http_Request**: Event tracking and logging
188+
3. **CORS**: Cross-origin resource sharing
189+
4. **API_Key_Check**: Header/cookie API key validation
190+
191+
### Custom Middleware
192+
193+
```python
194+
class Custom_Fast_API(Fast_API):
195+
def setup_middlewares(self):
196+
super().setup_middlewares() # Add default middleware
197+
198+
@self.app().middleware("http")
199+
async def add_process_time(request: Request, call_next):
200+
import time
201+
start = time.time()
202+
response = await call_next(request)
203+
response.headers["X-Process-Time"] = str(time.time() - start)
204+
return response
205+
```
206+
207+
## 🧪 Testing
208+
209+
Built-in test server with Type-Safe support:
210+
211+
```python
212+
from osbot_fast_api.utils.Fast_API_Server import Fast_API_Server
213+
214+
def test_api():
215+
fast_api = Fast_API()
216+
fast_api.setup()
217+
fast_api.add_routes(Routes_Users)
218+
219+
with Fast_API_Server(app=fast_api.app()) as server:
220+
# Test with Type-Safe object
221+
user_data = {'username': 'alice', 'email': 'alice@example.com', 'age': 30}
222+
response = server.requests_post('/users/create-user', data=user_data)
223+
224+
assert response.status_code == 200
225+
assert response.json()['created'] == 'alice'
226+
```
227+
228+
## 🚀 AWS Lambda Deployment
229+
230+
```python
231+
from mangum import Mangum
232+
from osbot_fast_api.api.Fast_API import Fast_API
233+
234+
# Create and setup application
235+
fast_api = Fast_API()
236+
fast_api.setup()
237+
fast_api.add_routes(Routes_Users)
238+
239+
# Create Lambda handler
240+
app = fast_api.app()
241+
handler = Mangum(app)
242+
243+
def lambda_handler(event, context):
244+
return handler(event, context)
245+
```
246+
247+
## 📁 Project Structure
248+
249+
```
250+
osbot_fast_api/
251+
├── api/
252+
│ ├── Fast_API.py # Main FastAPI wrapper
253+
│ ├── Fast_API_Routes.py # Route organization base class
254+
│ ├── Fast_API__Http_Event*.py # Event tracking components
255+
│ └── middlewares/ # Built-in middleware
256+
├── utils/
257+
│ ├── type_safe/ # Type conversion system
258+
│ │ ├── Type_Safe__To__BaseModel.py
259+
│ │ ├── BaseModel__To__Type_Safe.py
260+
│ │ └── ...
261+
│ ├── Fast_API_Server.py # Test server
262+
│ └── Fast_API_Utils.py # Utilities
263+
└── examples/ # Usage examples
264+
```
265+
266+
## 📚 Documentation
267+
268+
Comprehensive documentation is available in the [`/docs`](./docs) folder:
269+
270+
- [📖 Main Documentation](./docs/README.md)
271+
- [🏗️ Architecture Overview](./docs/architecture/osbot-fast-api-architecture.md)
272+
- [🔐 Type-Safe Integration](./docs/type-safe/type-safe-integration.md)
273+
- [📊 HTTP Events System](./docs/features/http-events-system.md)
274+
- [🛡️ Middleware Stack](./docs/features/middleware-stack.md)
275+
- [🚀 Quick Start Guide](./docs/guides/quick-start.md)
276+
- [🤖 LLM Prompts](./docs/guides/llm-prompts.md)
277+
- [🧪 Testing Guide](./docs/guides/testing.md)
278+
279+
## 🎯 Key Benefits
280+
281+
### For Developers
282+
- **Type Safety**: Catch errors at development time with Type_Safe validation
283+
- **Less Boilerplate**: Convention over configuration approach
284+
- **Auto-conversion**: Seamless type conversions at API boundaries
285+
- **Built-in Testing**: Integrated test server and utilities
286+
287+
### For Production
288+
- **Monitoring**: Comprehensive HTTP event tracking
289+
- **Security**: Built-in API key validation and header sanitization
290+
- **Performance**: Cached type conversions and efficient middleware
291+
- **AWS Ready**: Direct Lambda integration with Mangum
292+
293+
### For Teams
294+
- **Organized Code**: Clear separation with Fast_API_Routes classes
295+
- **Consistent Patterns**: Standardized route naming and structure
296+
- **Easy Testing**: Type-Safe test utilities
297+
- **Documentation**: Auto-generated OpenAPI/Swagger docs
298+
299+
## 🔧 Advanced Features
300+
301+
### Route Path Generation
302+
- `get_users()``/get-users`
303+
- `get_user__id()``/get-user/{id}`
304+
- `user__id_posts__post_id()``/user/{id}/posts/{post_id}`
305+
306+
### Type-Safe Primitives
307+
```python
308+
from osbot_utils.type_safe.Type_Safe__Primitive import Type_Safe__Primitive
309+
310+
class Email(Type_Safe__Primitive, str):
311+
def __new__(cls, value):
312+
if '@' not in value:
313+
raise ValueError("Invalid email")
314+
return super().__new__(cls, value)
315+
```
316+
317+
### Event Access in Routes
318+
```python
319+
from fastapi import Request
320+
321+
def get_request_info(self, request: Request):
322+
return {
323+
'event_id': str(request.state.request_id),
324+
'thread_id': request.state.request_data.http_event_info.thread_id
325+
}
326+
```
327+
328+
## 🤝 Contributing
329+
330+
Contributions are welcome! Please check the [documentation](./docs) for architecture details and patterns.
331+
332+
## 📄 License
333+
334+
This project is licensed under the Apache 2.0 License.
335+
336+
## 🔗 Related Projects
337+
338+
- [OSBot-Utils](https://github.com/owasp-sbot/OSBot-Utils) - Core Type-Safe implementation
339+
- [OSBot-AWS](https://github.com/owasp-sbot/OSBot-AWS) - AWS utilities
340+
- [OSBot-Fast-API-Serverless](https://github.com/owasp-sbot/OSBot-Fast-API-Serverless) - Serverless extensions
341+
342+
## 💡 Examples
343+
344+
For more examples, see:
345+
- [Basic FastAPI application](./docs/guides/quick-start.md)
346+
- [Type-Safe schemas](./docs/type-safe/type-safe-integration.md)
347+
- [Testing patterns](./docs/guides/testing.md)
348+
- [Real-world usage in MGraph-AI](./docs/type-safe/type-safe-integration.md#real-world-example-mgraph-ai-service)
349+
350+
---
351+
352+
**Built with ❤️ using Type-Safe principles for robust, maintainable APIs**

0 commit comments

Comments
 (0)