A lightning-fast web framework with FastAPI-compatible syntax and superior performance. Built on Starlette with Satya for ultra-efficient data validation, Tatsat delivers all the developer-friendly features of FastAPI with dramatically better performance.
Tatsat was created to solve a fundamental limitation: FastAPI is tightly coupled with Pydantic, making it nearly impossible to replace Pydantic with a faster validation system. Even when implementing custom route handlers in FastAPI, Pydantic is still used under the hood for request/response processing, severely limiting performance optimization potential.
The solution? Build a framework with FastAPI's elegant interface but powered by Satya, a validation library that delivers exceptional performance:
Tatsat outperforms FastAPI by a wide margin in both validation speed and HTTP request handling:
Payload Type | Tatsat + Satya | FastAPI + Pydantic | Improvement |
---|---|---|---|
Simple | 1,916,870 | 463,372 | 314% faster |
Medium | 1,704,724 | 483,471 | 253% faster |
Complex | 1,572,373 | 243,905 | 545% faster |
Metric | Tatsat | FastAPI | Improvement |
---|---|---|---|
Requests/sec | 20,438 | 7,310 | 179% faster |
Avg Latency | 0.22ms | 0.64ms | 66% lower |
See the benchmarks directory for detailed methodology and results
Tatsat provides everything FastAPI offers and more:
- Modern ASGI Framework: Built on Starlette, just like FastAPI
- Intuitive API: Similar interface to FastAPI for minimal learning curve
- Superior Validation: Satya's validation engine is 30x faster than Pydantic, 5x faster than msgspec
- Type Safety: Full support for Python type hints
- Automatic API Documentation: Swagger UI and ReDoc integration
- Powerful Dependency Injection: Clean, modular code with dependency management
- Path Operations: Intuitive route decorators for all HTTP methods
- Advanced Middleware Support: Flexible middleware system
- Exception Handling: Comprehensive exception management
- APIRouter: Route organization with prefixes and tags
- WebSocket Support: Real-time bi-directional communication
- Background Tasks: Efficient asynchronous task processing
- Security Utilities: OAuth2, JWT, and other authentication systems
- Testing Utilities: Easy endpoint testing
Satya achieves its remarkable performance through:
- Optimized Type Checking: Highly efficient type validation algorithms
- Reduced Object Overhead: Minimized memory allocations during validation
- Custom Validator Compilation: Runtime-optimized validator functions
- Pure Python Implementation: No complex C-extensions, yet better performance
- Efficient Error Handling: Streamlined error reporting with minimal overhead
- Fewer Nested Function Calls: Flatter execution path for faster validation
- Type Coercion Optimizations: Smart type conversions without unnecessary operations
# Install from PyPI
pip install tatsat
# Or install directly from the repository
pip install -e .
# Make sure you have satya installed
pip install satya
Here's a minimal example to get you started:
from tatsat import Tatsat
from satya import Model, Field
from typing import List, Optional
app = Tatsat(title="Tatsat Demo")
# Define your data models with Satya
class Item(Model):
name: str = Field()
description: Optional[str] = Field(required=False)
price: float = Field(gt=0)
tax: Optional[float] = Field(required=False)
tags: List[str] = Field(default=[])
# Create API endpoints with typed parameters
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
@app.post("/items/", response_model=Item)
def create_item(item: Item):
return item
# Run the application with Uvicorn
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
The Tatsat
class is the main entry point for creating web applications:
from tatsat import Tatsat
app = Tatsat(
title="Tatsat Example API",
description="A sample API showing Tatsat features",
version="0.1.0",
debug=False
)
Tatsat provides decorators for all standard HTTP methods:
@app.get("/")
@app.post("/items/")
@app.put("/items/{item_id}")
@app.delete("/items/{item_id}")
@app.patch("/items/{item_id}")
@app.options("/items/")
@app.head("/items/")
Path parameters are part of the URL path and are used to identify a specific resource:
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
Query parameters are optional parameters appended to the URL:
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
Request bodies are parsed and validated using Satya models:
@app.post("/items/")
def create_item(item: Item):
return item
Tatsat includes a powerful dependency injection system:
def get_db():
db = Database()
try:
yield db
finally:
db.close()
@app.get("/items/")
def read_items(db = Depends(get_db)):
return db.get_items()
Specify response models for automatic serialization and documentation:
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
return get_item_from_db(item_id)
Tatsat supports efficient background task processing without blocking the main request:
from tatsat import BackgroundTasks
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email_notification, email, message="Welcome!")
return {"message": "Notification will be sent in the background"}
For more complex task processing, Tatsat can integrate with:
- asyncio.create_task() for simple async tasks
- arq for Redis-based task queues
- Celery for distributed task processing
- Dramatiq for simple but powerful task processing
Organize your routes using the APIRouter
:
from tatsat import APIRouter
router = APIRouter(prefix="/api/v1")
@router.get("/items/")
def read_items():
return {"items": []}
app.include_router(router)
Add middleware for cross-cutting concerns:
@app.middleware("http")
async def add_process_time_header(request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
Custom exception handlers:
@app.exception_handler(404)
async def not_found_exception_handler(request, exc):
return JSONResponse(
status_code=404,
content={"message": "Resource not found"}
)
Real-time bi-directional communication:
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message received: {data}")
Comprehensive security features:
from tatsat.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Invalid credentials")
return {"access_token": create_access_token(user), "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
user = get_current_user(token)
return user
Tatsat combines the best of both worlds:
- Familiar API: If you know FastAPI, you already know Tatsat
- Exceptional Performance: 30x faster validation, 2x higher HTTP throughput
- True Framework Independence: Built from the ground up to avoid Pydantic dependency
- Production Ready: Built with performance and reliability in mind
- Feature Complete: Everything FastAPI has, with superior performance
- Future Proof: Actively maintained and improved
Tatsat is actively being developed with a focus on:
- Even Better Performance: Continuous optimization efforts
- Enhanced Validation Features: More validation options with Satya
- Advanced Caching: Integrated caching solutions
- GraphQL Support: Native GraphQL endpoint creation
- More Middleware: Additional built-in middleware options
- Examples: Practical examples for various use cases
- Benchmarks: Detailed performance comparisons
- Documentation: Comprehensive documentation
This project is licensed under the MIT License - see the LICENSE file for details.
Tatsat builds upon the excellent work of the Starlette and FastAPI projects, offering a compatible API with dramatically improved performance.