Skip to main content

pyboot-web

pyboot-web is the Starlette integration for PyBoot. It discovers annotated classes in a PyBoot application, registers them with the IoC container, and adds HTTP routes, middleware, exception handling, CORS, environment loading, and scheduled background jobs.

The current package creates the Starlette application inside RestPlugin. PyBoot remains responsible for discovery, dependency injection, and plugin lifecycle orchestration.

Requirements and installation

Python 3.11 or newer is required.

python -m pip install pyboot-framework pyboot-web uvicorn

For this repository:

python -m pip install -e pyboot
python -m pip install -e plugins/pyboot_web

The package depends on Starlette, Pydantic, and python-dotenv. Uvicorn is needed to serve the resulting ASGI application.

Verify installed entry points:

python -c "from importlib.metadata import entry_points; print([e.name for e in entry_points(group='pyboot.plugins')])"

The output should include RestPlugin, ServicePlugin, WebComponentPlugin, MiddlewareComponentPlugin, and ValuePlugin.

Minimal application

Keep application classes below the package passed to bootstrap():

my-service/
├── main.py
└── app/
    ├── __init__.py
    └── controllers.py

app/controllers.py:

from starlette.requests import Request
from starlette.responses import JSONResponse

from pyboot_web.rest_mapping import GetMapping, RestController


@RestController("/api")
class HealthController:
    @GetMapping("/health")
    async def health(self, request: Request) -> JSONResponse:
        return JSONResponse({"status": "ok"})

main.py:

from pyboot import PyBoot
from pyboot_web.plugins.RestPlugin import RestPlugin


boot = PyBoot(debug=False)
boot.bootstrap(package="app")
app = boot.get_plugin(RestPlugin).app

Run the ASGI application:

python -m uvicorn main:app --host 127.0.0.1 --port 8000
curl http://127.0.0.1:8000/api/health

RestPlugin owns the Starlette instance. Do not pass an application object to PyBoot; the current core constructor is PyBoot(debug=False).

Route mappings

Supported decorators are GetMapping, PostMapping, PutMapping, PatchMapping, and DeleteMapping. They must be used on methods declared inside a RestController:

from starlette.requests import Request
from starlette.responses import JSONResponse

from pyboot_web.rest_mapping import (
    DeleteMapping,
    GetMapping,
    PatchMapping,
    PostMapping,
    PutMapping,
    RestController,
)


@RestController("/api/users")
class UserController:
    @GetMapping("")
    async def list_users(self, request: Request) -> JSONResponse:
        return JSONResponse({"items": []})

    @GetMapping("/{user_id}")
    async def get_user(self, request: Request) -> JSONResponse:
        return JSONResponse({"id": request.path_params["user_id"]})

    @PostMapping("")
    async def create_user(self, request: Request) -> JSONResponse:
        return JSONResponse(await request.json(), status_code=201)

    @PutMapping("/{user_id}")
    async def replace_user(self, request: Request) -> JSONResponse:
        return JSONResponse({"id": request.path_params["user_id"]})

    @PatchMapping("/{user_id}")
    async def update_user(self, request: Request) -> JSONResponse:
        return JSONResponse({"id": request.path_params["user_id"]})

    @DeleteMapping("/{user_id}")
    async def delete_user(self, request: Request) -> JSONResponse:
        return JSONResponse({}, status_code=204)

Controller and route paths are joined after trimming duplicate slashes. Starlette supplies path parameters through request.path_params, query values through request.query_params, and headers through request.headers.

Services and components

Use WebService() for web-layer services:

from pyboot_web.service import WebService


@WebService()
class UserService:
    def find_user(self, user_id: str) -> dict[str, str]:
        return {"id": user_id, "name": "Ada"}

Use PyBoot's Component() for general application dependencies:

from pyboot.core.builtins.component import Component


@Component()
class AuditService:
    def record(self, message: str) -> None:
        print(message)

Both kinds of classes can be injected into controllers and services through annotated constructors:

from pyboot_web.rest_mapping import GetMapping, RestController
from app.services import UserService


@RestController("/users")
class UserController:
    def __init__(self, users: UserService) -> None:
        self.users = users

    @GetMapping("/{user_id}")
    async def get_user(self, request):
        return {"user": self.users.find_user(request.path_params["user_id"])}

Use WebComponent() when a class is a web-plugin-specific managed component. The package root does not re-export these decorators; import them from pyboot_web.service and pyboot_web.component.

Middleware

Implement MiddlewareBase, mark it with MiddlewareComponent(), and apply the class with UseMiddleware():

from starlette.requests import Request
from starlette.responses import Response

from pyboot_web.middlewares import (
    CallNext,
    MiddlewareBase,
    MiddlewareComponent,
    UseMiddleware,
)


@MiddlewareComponent()
class RequestIdMiddleware(MiddlewareBase):
    async def __call__(
        self,
        request: Request,
        call_next: CallNext,
    ) -> Response:
        response = await call_next(request)
        response.headers["x-request-id"] = request.headers.get(
            "x-request-id", "generated-request-id"
        )
        return response

Apply middleware to a controller or one route:

@RestController("/api")
@UseMiddleware([RequestIdMiddleware])
class HealthController:
    @GetMapping("/health")
    async def health(self, request: Request) -> JSONResponse:
        return JSONResponse({"status": "ok"})

Pass middleware classes, not instances. Controller middleware wraps route middleware, which wraps the endpoint.

Exception handling

Use RestControllerAdvice() and ExceptionHandler():

from starlette.requests import Request
from starlette.responses import JSONResponse

from pyboot_web.exception_handler import ExceptionHandler, RestControllerAdvice


class UserNotFoundError(Exception):
    pass


@RestControllerAdvice()
class ApiExceptionAdvice:
    @ExceptionHandler(UserNotFoundError)
    def user_not_found(
        self,
        request: Request,
        exception: UserNotFoundError,
    ) -> JSONResponse:
        return JSONResponse({"error": str(exception)}, status_code=404)

Handlers receive (request, exception) after self. Resolution checks the exception type and then its method-resolution order. Duplicate registrations are rejected; unhandled exceptions are re-raised.

Environment values

ValuePlugin loads a .env file from the current working directory before class discovery using override=True:

from pyboot_web.value import Value


SERVICE_NAME = Value("SERVICE_NAME", "user-api")
PORT = int(Value("PORT", "8000"))
DEBUG = Value("DEBUG", "false").lower() == "true"

Value(key, default) returns a string environment value or the default. If both are None, it raises MissingValueException. Convert values explicitly at the configuration boundary.

CORS

Provide a CorsConfiguration bean for RestPlugin to install Starlette's CORS middleware:

from pyboot.core.builtins.configuration import Bean, Configuration
from pyboot_web.cors import CorsConfiguration


@Configuration()
class WebConfiguration:
    @Bean()
    def cors(self) -> CorsConfiguration:
        return CorsConfiguration(
            allowed_origins=["http://localhost:3000"],
            allowed_methods=["GET", "POST"],
            allowed_headers=["content-type"],
        )

Background jobs

BackgroundService classes can schedule methods with IntervalSchedule, FixedDelaySchedule, or CronJob:

from pyboot_web.bg_service import (
    BackgroundService,
    IntervalSchedule,
)


@BackgroundService()
class CleanupJobs:
    @IntervalSchedule(interval_ms=60_000, initial_delay_ms=5_000)
    async def cleanup(self) -> None:
        print("cleanup")

The scheduler starts with the Starlette lifespan and shuts down when the application exits. Interval and fixed-delay values must be positive; cron expressions use APScheduler's crontab syntax.

Lifecycle and discovery

PyBoot loads all installed pyboot.plugins entry points, scans the requested package, and then invokes plugin hooks. The web plugins register services, components, middleware, controllers, exception advice, and jobs during the registration/loading phases.

Use PyBoot.get_plugin(RestPlugin) to access the Starlette application after bootstrap. Use PyBoot.get_context() to access the IoC container and resources.

Testing

from starlette.testclient import TestClient

from pyboot import PyBoot
from pyboot_web.plugins.RestPlugin import RestPlugin


def test_health() -> None:
    boot = PyBoot()
    boot.bootstrap("app")
    client = TestClient(boot.get_plugin(RestPlugin).app)

    response = client.get("/api/health")
    assert response.status_code == 200
    assert response.json() == {"status": "ok"}

License

MIT. See LICENSE.

Metadata

Release files for pyboot-web 0.1.14

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyboot-web 0.1.14
File Size Uploaded Provenance Actions
pyboot_web-0.1.14.tar.gz 15.6 kB Without provenance Details for pyboot_web-0.1.14.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyboot-web 0.1.14
File Interpreter ABI Platform Actions
pyboot_web-0.1.14-py3-none-any.whl Python 3 none any Details for pyboot_web-0.1.14-py3-none-any.whl

Total release size: 32.6 kB

Release files / pyboot_web-0.1.14.tar.gz

Download URL pyboot_web-0.1.14.tar.gz
Size 15.6 kB
Tags Source
SHA-256 checksum
How to use checksums
a4f12139473abd92c44cfb24b486d2fefce66f0aef4865bac6c9dc2b682d1381
BLAKE2b-256 checksum
How to use checksums
1a78dd0e2f23f3e46add56a8a8dab3a248826b0a91523187debcff1da3f70c7e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / pyboot_web-0.1.14-py3-none-any.whl

Download URL pyboot_web-0.1.14-py3-none-any.whl
Size 17.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab48334af94b28d83e59567968227f68b9c6e8df55b6259b953c847db0a3c66d
BLAKE2b-256 checksum
How to use checksums
841632c81104c93ec99652d9c7e8fce0a81f345077fd95c3fc022912f8a1b449
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for pyboot-web 0.1.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page