Skip to main content

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, timestamp
  • GET /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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

viveka_setu-0.1.0.tar.gz (16.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

viveka_setu-0.1.0-py3-none-any.whl (15.5 kB view details)

Uploaded Python 3

File details

Details for the file viveka_setu-0.1.0.tar.gz.

File metadata

  • Download URL: viveka_setu-0.1.0.tar.gz
  • Upload date:
  • Size: 16.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for viveka_setu-0.1.0.tar.gz
Algorithm Hash digest
SHA256 810aaadae0d527b10a425df516600f6afa650a14cebada8853d6158c28af53a2
MD5 11e668cc9dbde9e614b6915fa7e75f57
BLAKE2b-256 faa9957caaa607006a29638ec2735b137b352db1dd4c807a66cce4dcc8e997e6

See more details on using hashes here.

File details

Details for the file viveka_setu-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: viveka_setu-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 15.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for viveka_setu-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 724d4fd4f2904ab13c1bf97e85f8b99d4b1fe8527b7f1aaead0c0367459d8864
MD5 a7b3e13bd66861c237e36145bf1f598d
BLAKE2b-256 f51318315ace9b9324f5511527301d9f9fe5ac074eb511e915964a5e446dd61b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page