A high-performance web framework with elegant syntax and powerful validation using satya
Project description
What is TurboAPI?
TurboAPI is a lightning-fast ASGI web framework designed for speed without sacrificing developer experience. It combines:
- FastAPI-compatible syntax - Familiar API with minimal learning curve
- Starlette foundation - Robust, battle-tested ASGI implementation
- Satya validation - Ultra-efficient data validation (30x faster than Pydantic)
- Complete authentication system - JWT, OAuth2, and Basic authentication built-in
If you like FastAPI but need better performance, TurboAPI is the framework you've been waiting for.
🎯 Why Choose TurboAPI?
- You need better performance - FastAPI's tight coupling with Pydantic creates a performance bottleneck
- You love the FastAPI syntax - TurboAPI preserves the developer-friendly API you already know
- You want modern features - All the goodies: dependency injection, auto docs, type hints, etc.
- You value simplicity - Drop-in replacement with minimal learning curve
⚡ Performance Highlights
TurboAPI outperforms FastAPI by a wide margin in both validation speed and HTTP request handling:
🚀 Validation Performance
TurboAPI's validation engine is 31.3x faster than FastAPI + Pydantic
🔥 HTTP Performance
- 2.8x more requests per second - Handle more traffic with the same hardware
- 66% lower latency - More responsive applications
- ~50% faster response times - Recent benchmarks show TurboAPI outperforms FastAPI by approximately 45-50% in API operations
📊 TurboAPI vs FastAPI Benchmark
Our latest benchmark comparing TurboAPI and FastAPI demonstrates significant performance advantages:
# Run the benchmark yourself
python examples/turboapi_fastapi_benchmark.py
Results consistently show TurboAPI processing requests with about half the latency of FastAPI across various payload sizes and operation types.
🌟 Key Features
| Feature | Description |
|---|---|
| 🔍 FastAPI-compatible API | Everything you love about FastAPI's interface |
| ⚡ 30x faster validation | Satya validation engine outperforms Pydantic |
| 📘 Automatic API docs | Swagger UI and ReDoc integration |
| 💉 Dependency injection | Clean, modular code with dependency management |
| 🔄 WebSockets | Real-time bi-directional communication |
| 🔒 Complete auth system | JWT, OAuth2, and Basic authentication with middleware support |
| 🧩 API Router | Organize routes with prefixes and tags |
| 🔄 Background tasks | Efficient asynchronous task processing |
🔒 Authentication Features
TurboAPI includes a comprehensive authentication system with:
- OAuth2 Password Flow - Authenticate using username and password
- JWT Authentication - Industry-standard token authentication
- Basic Authentication - Simple username/password auth for internal services
- Custom Auth Backends - Create your own authentication strategies
- Middleware Integration - Secure your app at the middleware level
- Authorization Scopes - Fine-grained access control
- Path Exclusion - Exclude specific paths from authentication requirements
⚙️ Installation
# From PyPI
pip install turboapi
# Installs all dependencies including Satya
🚀 Quick Start
from turboapi import TurboAPI
from satya import Model, Field
from typing import List, Optional
app = TurboAPI(title="TurboAPI Demo")
# Define models with Satya (30x faster than Pydantic)
class Item(Model):
name: str = Field()
price: float = Field(gt=0)
tags: List[str] = Field(default=[])
description: Optional[str] = Field(required=False)
# API with typed parameters - just like FastAPI
@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/")
def create_item(item: Item):
return item.to_dict()
# Run the application with Uvicorn
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
🔒 Authentication Example
Here's a simple example of using JWT authentication:
from turboapi import TurboAPI, Depends, HTTPException, JWTAuthentication
from turboapi.middleware import JWTAuthMiddleware
from satya import Model, Field
# Define your app with JWT authentication middleware
app = TurboAPI(
title="Secure API",
middleware=[
Middleware(JWTAuthMiddleware,
secret_key="your-secret-key",
excluded_paths=["/token", "/docs"])
]
)
# User model
class User(Model, BaseUser):
username: str = Field()
email: str = Field()
@property
def identity(self) -> str:
return self.username
# Authentication dependency
async def get_current_user(request):
# The user is already set by the middleware
if not request.user.is_authenticated:
raise HTTPException(status_code=401, detail="Not authenticated")
return request.user
# Protected endpoint
@app.get("/me")
async def read_users_me(current_user = Depends(get_current_user)):
return {"username": current_user.username}
🧩 Core Concepts
Application
The TurboAPI class is the main entry point for creating web applications:
from turboapi import TurboAPI
app = TurboAPI(
title="TurboAPI Example API",
description="A sample API showing TurboAPI features",
version="0.1.0",
debug=False
)
Path Operations
TurboAPI 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
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
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 Body
Request bodies are parsed and validated using Satya models:
@app.post("/items/")
def create_item(item: Item):
return item
Dependency Injection
TurboAPI 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()
Response Models
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)
🔋 Advanced Features
Background Tasks
TurboAPI supports efficient background task processing without blocking the main request:
from turboapi 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, TurboAPI 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
API Routers
Organize your routes using the APIRouter:
from turboapi import APIRouter
router = APIRouter(prefix="/api/v1")
@router.get("/items/")
def read_items():
return {"items": []}
app.include_router(router)
Middleware
Add middleware for cross-cutting concerns:
from turboapi import Middleware
# Add middleware at app initialization
app = TurboAPI(
middleware=[
Middleware(CORSMiddleware, allow_origins=["*"]),
Middleware(AuthenticationMiddleware, backend=JWTAuthentication(...))
]
)
Exception Handlers
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"}
)
WebSockets
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}")
OAuth2 and Security
Comprehensive security features:
from turboapi 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
📈 Why Choose TurboAPI Over FastAPI?
TurboAPI combines the best of both worlds:
- Familiar API: If you know FastAPI, you already know TurboAPI
- 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
🎯 Why TurboAPI Exists
TurboAPI 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. This architectural decision allows TurboAPI to maintain API compatibility while achieving dramatic performance improvements.
🔮 What's Next?
TurboAPI 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
📚 Learning Resources
- Examples: Practical examples for various use cases
- Benchmarks: Detailed performance comparisons
- Documentation: Comprehensive documentation
📜 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgements
TurboAPI builds upon the excellent work of the Starlette and FastAPI projects, offering a compatible API with dramatically improved performance.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file turboapi-0.2.7.tar.gz.
File metadata
- Download URL: turboapi-0.2.7.tar.gz
- Upload date:
- Size: 28.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
099f4d798e9513f181f4bd62f99832412d13295ee41f5d05659e03031cf5f09d
|
|
| MD5 |
629666a0018803cd895d8460c263ee33
|
|
| BLAKE2b-256 |
e1410a248111cc20a3041be4c7cb1078beee2ad9763f976d17fe42ab4fa1dbc7
|
File details
Details for the file turboapi-0.2.7-py3-none-any.whl.
File metadata
- Download URL: turboapi-0.2.7-py3-none-any.whl
- Upload date:
- Size: 24.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
286bae2988411b7d9bf7a775f8f797a67d2d7a27ecb1fdadfcc6e392e95087a9
|
|
| MD5 |
477b37f96348246eeeb94a9a6858e2c1
|
|
| BLAKE2b-256 |
020208c8f5134b0d74141a897fbc8332887e495a462dd04670fcf5e3ccb82703
|