FastAPI + Uvicorn application factory for Viveka services — built-in health, CORS, exception handling, and lifecycle management
Project description
viveka-setu
FastAPI + Uvicorn application factory for Viveka services. Spin up a production-ready API server with built-in health checks, CORS, exception handling, DB middleware, and lifecycle management — in under ten lines of code.
Developed by VivekaSutra
Overview
viveka-setu is the equivalent of Spring Boot's embedded Tomcat + @SpringBootApplication. It wraps FastAPI and Uvicorn so developers focus on business logic, not server boilerplate.
| Feature | Detail |
|---|---|
| Built-in routes | GET / (status) and GET /health (uptime + version) |
| CORS | Configurable origins via config.ini or defaults to * |
| Exception handling | Standard JSON error responses for all HTTP error types |
| DB middleware | Auto-wired DbMiddleware when enable_database=True |
| Cache | Auto-wired Redis cache when enable_cache=True |
| Lifecycle hooks | startup() and shutdown() overridable in VivekaApp |
| CLI args | --host, --port, --reload, --workers, --log-level |
| Config priority | CLI args → config.ini → hardcoded defaults |
Installation
pip install viveka-setu
With database support (viveka-kosha):
pip install "viveka-setu[database]"
Quickstart
from viveka_server import VivekaApp, VivekaServer, VivekaAppConfig
app = VivekaApp(VivekaAppConfig(name="my-service", version="1.0.0"))
server = VivekaServer(app)
server.run()
That's it. Your service is running at http://127.0.0.1:8000 with:
GET /→{"service": "my-service", "version": "1.0.0", "status": "running"}GET /health→ uptime, name, version, timestampGET /docs→ FastAPI Swagger UI
Configuration
config.ini:
[server]
host = 0.0.0.0
port = 8080
reload = false
workers = 4
log_level = info
[api]
cors_origins = https://myapp.com, https://admin.myapp.com
[logging]
level = INFO
file_path = logs/service.log
[database]
url = postgresql+asyncpg://user:pass@localhost/mydb
pool_size = 10
max_overflow = 20
[cache]
enabled = true
url = redis://localhost:6379/0
default_ttl = 3600
Adding Custom Routes
Override build_routes() in a VivekaServer subclass:
from fastapi import APIRouter
from viveka_server import VivekaApp, VivekaServer, VivekaAppConfig
class MyServer(VivekaServer):
def build_routes(self, router: APIRouter) -> APIRouter:
@router.get("/api/v1/ping")
async def ping():
return {"pong": True}
@router.get("/api/v1/users/{user_id}")
async def get_user(user_id: int):
return {"id": user_id}
return router
app = VivekaApp(VivekaAppConfig(name="my-service", version="1.0.0"))
server = MyServer(app)
server.run()
Lifecycle Hooks
Override startup() and shutdown() in a VivekaApp subclass for custom initialization:
from viveka_server import VivekaApp, VivekaAppConfig
class MyApp(VivekaApp):
async def startup(self) -> None:
await super().startup()
# load ML models, warm caches, connect external services
self.logger.info("Custom startup complete")
async def shutdown(self) -> None:
# release resources, flush buffers
self.logger.info("Custom shutdown complete")
await super().shutdown()
Enable Database & Cache
from viveka_server import VivekaApp, VivekaServer, VivekaAppConfig
app = VivekaApp(VivekaAppConfig(
name = "data-service",
version = "1.0.0",
enable_database = True, # auto-wires DbMiddleware + DatabaseSessionFactory
enable_cache = True, # auto-wires VivekaCacheManager + RedisCacheService
))
server = VivekaServer(app)
server.run()
Requires [database] and [cache] sections in config.ini.
Requires pip install "viveka-setu[database]" for DB support.
Exception Handling
viveka-setu registers a global exception handler that converts all VivekaAPIException subclasses to a consistent JSON response:
{
"success": false,
"error": {
"code": "NOT_FOUND",
"message": "User not found",
"details": {}
}
}
Raise exceptions directly from any route or service:
from viveka_server import NotFoundException, UnauthorizedException, RateLimitException
@router.get("/users/{user_id}")
async def get_user(user_id: int):
user = await user_repo.get(user_id)
if not user:
raise NotFoundException(f"User {user_id} not found")
return user
Available Exceptions
| Class | HTTP Code | Error Code |
|---|---|---|
NotFoundException |
404 | NOT_FOUND |
ValidationException |
400 | VALIDATION_ERROR |
UnauthorizedException |
401 | UNAUTHORIZED |
ForbiddenException |
403 | FORBIDDEN |
InternalServerException |
500 | INTERNAL_ERROR |
RateLimitException |
429 | RATE_LIMIT_EXCEEDED |
BudgetExceededException |
402 | BUDGET_EXCEEDED |
TimeoutException |
504 | TIMEOUT_ERROR |
ProviderException |
502 | PROVIDER_ERROR |
CLI Usage
python main.py --host 0.0.0.0 --port 8080 --workers 4
python main.py --reload # development mode
python main.py --log-level debug
Part of the Viveka Platform
- viveka-grantha — config, logging, cache (required)
- viveka-kosha — async database / ORM (optional, for
enable_database=True) - viveka-setu — server factory ← you are here
License
Copyright (c) 2025 VivekaSutra. All rights reserved.
This software is distributed under the VivekaSutra Proprietary Software License.
- Free to download and use for personal or commercial purposes
- Modification, redistribution, and reverse engineering are not permitted
- Provided "AS IS" — no warranty of any kind
- VivekaSutra is not liable for any damages arising from use
See LICENSE.txt for the full license text. For licensing inquiries visit vivekasutra.com
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 viveka_setu-0.1.1.tar.gz.
File metadata
- Download URL: viveka_setu-0.1.1.tar.gz
- Upload date:
- Size: 16.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0162a462e8f8c74a300ed366e41920c777e65a6d49eb7f9e870fff1685e9f29e
|
|
| MD5 |
9b5ee540247e068482dfd6a8ff2630e2
|
|
| BLAKE2b-256 |
8874f7bbc3107a65ae2e4f8d247dd95f616deaa0dbb208002f1d7a575405d628
|
File details
Details for the file viveka_setu-0.1.1-py3-none-any.whl.
File metadata
- Download URL: viveka_setu-0.1.1-py3-none-any.whl
- Upload date:
- Size: 15.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
329ee59105a45a0c8efe0a501f99516bee2d4e0de31967eb3ce8e64d625a2226
|
|
| MD5 |
4163a528a8de41fb88001a391d19c553
|
|
| BLAKE2b-256 |
e3073f5154a6e1bfbe4a4d57685f89f8d4014fb001d609e02be39064309e727e
|