Metadata-Version: 2.4
Name: pyboot-web
Version: 0.1.14
Summary: Starlette web plugin for PyBoot
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyboot-framework>=0.1.0
Requires-Dist: starlette>=0.40.0
Requires-Dist: pydantic>=2.0
Requires-Dist: python-dotenv>=1.0.0
Dynamic: license-file

# pyboot-web

`pyboot-web` is the Starlette integration for
[PyBoot](../../pyboot/README.md). 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.

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

For this repository:

```bash
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:

```bash
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()`:

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

`app/controllers.py`:

```python
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`:

```python
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:

```bash
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`:

```python
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:

```python
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:

```python
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:

```python
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()`:

```python
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:

```python
@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()`:

```python
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`:

```python
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:

```python
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`:

```python
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

```python
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"}
```

## Related documentation

- [Examples](./EXAMPLES.md)
- [Production starter](./STARTER.md)
- [Core PyBoot README](../../pyboot/README.md)
- [Core PyBoot examples](../../pyboot/examples.md)

## License

MIT. See [LICENSE](./LICENSE).
