Metadata-Version: 2.4
Name: lambroute
Version: 0.1.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Rust
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Typing :: Typed
Requires-Dist: lambroute[validation] ; extra == 'all'
Requires-Dist: lambroute[validation] ; extra == 'dev'
Requires-Dist: maturin>=1.7,<2.0 ; extra == 'dev'
Requires-Dist: pytest>=8 ; extra == 'dev'
Requires-Dist: pytest-cov>=5 ; extra == 'dev'
Requires-Dist: ruff>=0.6 ; extra == 'dev'
Requires-Dist: mypy>=1.10 ; extra == 'dev'
Requires-Dist: pylint>=3.3 ; extra == 'dev'
Requires-Dist: pydantic>=2.5,<3 ; extra == 'validation'
Requires-Dist: email-validator>=2.0 ; extra == 'validation'
Provides-Extra: all
Provides-Extra: dev
Provides-Extra: validation
License-File: LICENSE
Summary: Lambda + Route + Swagger: a lightweight, Rust-accelerated REST API framework for AWS Lambda with automatic OpenAPI docs.
Keywords: aws,lambda,api-gateway,serverless,rest,openapi,swagger,rust
Author: lambroute maintainers
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/lambroute/lambroute/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/lambroute/lambroute/tree/main/docs
Project-URL: Homepage, https://github.com/lambroute/lambroute
Project-URL: Issues, https://github.com/lambroute/lambroute/issues

# lambroute

**Lambda + Route + Swagger.** A lightweight Python API framework for AWS Lambda,
with a Rust routing core and auto-generated OpenAPI/Swagger docs.

Write plain Python functions; lambroute handles routing, parameter parsing,
validation, responses, errors, CORS, auth hooks and OpenAPI/Swagger for
API Gateway (REST API, HTTP API 1.0 / 2.0) and Lambda Function URLs.

```bash
pip install lambroute                 # core: zero runtime dependencies
pip install "lambroute[validation]"   # + Pydantic v2 request/response models
```

Supported: CPython 3.10–3.14 · Linux x86_64 / arm64 (manylinux2014, AWS Lambda), macOS, Windows.
One `abi3` wheel per platform covers every supported Python version.

## Quick start

```python
from lambroute import API

app = API(title="Customer Management API", version="1.0.0", swagger=True)

@app.get("/customers")
def get_customers(limit: int = 20):
    return {"success": True, "data": []}

@app.get("/customers/{customer_id}")
def get_customer(customer_id: str):
    return {"customer_id": customer_id}

@app.post("/customers", status_code=201)
def create_customer(request):            # `request` (or `r: Request`) injects the Request
    return {"received": request.json()}

def lambda_handler(event, context):
    return app.resolve(event, context)   # or simply: lambda_handler = app
```

`GET /docs` serves Swagger UI, `/redoc` ReDoc, and `/openapi.json` the spec — all
generated from the same route registry used for routing.

## Features

| Area | What you get |
|---|---|
| Routing | `@app.get/post/put/patch/delete/options/head`, `{param}` and greedy `{proxy+}` paths, static-over-dynamic priority with backtracking, `Router(prefix=…)` modules (nestable), duplicate/conflict detection at import time, 404 / 405 + `Allow`, HEAD→GET, configurable trailing slashes, `strip_prefixes` and automatic stage stripping |
| Parameters | Bound from the signature: path, query (`list[int]` for repeated keys), headers (`Header()`), body (Pydantic model or `Body()`), `Request` injection, `Annotated[..., Query(alias=…), Ge(1)]` |
| Validation | Built-in coercion for `str/int/float/bool/Decimal/UUID/date/datetime/Enum/Literal/Optional/list` (no Pydantic needed); Pydantic v2 models, constraints and `response_model` when installed. All errors are collected into one 422 |
| Responses | dict/list/scalars → JSON, `str` → text, `bytes` → base64 binary, `None` → 204, `(body, status[, headers])` tuples, `Response`/`JSONResponse`, cookies, pluggable `ResponseSerializer` / envelope |
| Errors | `HTTPException` hierarchy, `@app.exception_handler(...)`, uniform JSON error body with `request_id`, no stack traces or exception messages leaked (opt-in `debug`), pluggable `error_formatter` |
| Middleware | `(request, call_next) -> Response`, deterministic order, `RequestLoggingMiddleware` (structured, never logs bodies), `SecurityHeadersMiddleware` |
| Auth | `APIKeyAuth` (constant-time), `BearerAuth(verifier)` (bring PyJWT or anything), custom providers, app/router/route level, `public=True`, `authorize=` → 403 |
| CORS | `CORSConfig` with exact/regex origins, credentials safety check, automatic preflight |
| Async | `async def` handlers on a reused per-environment event loop |
| Testing | `lambroute.testing.TestClient` + event builders for all three payload formats |

## Validation example

```python
from pydantic import BaseModel, EmailStr
from lambroute import API

app = API(swagger=True)

class EmployeeCreate(BaseModel):
    name: str
    email: EmailStr
    department: str

@app.post("/employees", request_model=EmployeeCreate, status_code=201)
def create_employee(body: EmployeeCreate):
    return {"name": body.name, "email": body.email}
```

Invalid input yields:

```json
{"error": {"code": "validation_error", "message": "Request validation failed",
  "details": [{"loc": ["body", "email"], "msg": "value is not a valid email address: ...", "type": "value_error"}],
  "request_id": "c6af9ac6-..."}}
```

## Modular routers, auth and CORS

```python
from lambroute import API, APIKeyAuth, BearerAuth, CORSConfig, Router

app = API(
    auth=BearerAuth(lambda token, request: verify_jwt(token)),   # default for all routes
    cors=CORSConfig(allow_origins=["https://app.example.com"]),
    swagger=True,
    docs_auth=APIKeyAuth(keys=["docs-secret"]),                 # protect /docs in prod
)

customers = Router(prefix="/customers", tags=["customers"])

@customers.get("/{customer_id}", authorize=lambda r: "read" in r.principal["scopes"])
def get_customer(customer_id: int):
    ...

@app.get("/health", public=True)
def health():
    return "ok"

app.include_router(customers)
```

## Testing without AWS

```python
from lambroute.testing import TestClient

client = TestClient(app)                          # HTTP API v2 events
assert client.get("/customers/1", headers={"Authorization": "Bearer t"}).status_code == 200
TestClient(app, event_format="rest")              # REST API proxy events
TestClient(app, event_format="http-v1")           # HTTP API payload 1.0
```

## Configuration (environment)

| Variable | Default | Effect |
|---|---|---|
| `LAMBROUTE_DEBUG` | `false` | Adds exception type/message (never tracebacks) to 500 bodies |
| `LAMBROUTE_DOCS_ENABLED` | `true` | `false` turns docs off even if `swagger=True` |
| `LAMBROUTE_ENGINE` | `auto` | `native` (require Rust), `python` (force fallback) |

## Performance

Routing runs in a Rust trie (PyO3) with exactly one Python→Rust call per
request. On x86_64 / Python 3.13 it matches routes 3–5× faster than the
identical pure-Python engine, flat from 10 to 10,000 routes (~0.15 µs static,
~0.4 µs dynamic). Because routing is a small part of a request, the full
event→response pipeline is ~1.1–1.2× faster (≈9 µs vs ≈10 µs). Import plus
`API()` is ≈35 ms with either engine. Full method and numbers:
[docs/benchmarks.md](docs/benchmarks.md).

If no native wheel is available, lambroute falls back to the pure-Python
engine (identical behaviour, verified by a randomized parity test) and logs a
warning; set `LAMBROUTE_ENGINE=native` to fail fast instead.

## Documentation

- [Architecture & request lifecycle](docs/architecture.md)
- [Deploying to AWS Lambda](docs/deployment.md)
- [Benchmarks](docs/benchmarks.md)
- [Examples](examples/)
- [Changelog](CHANGELOG.md)

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"            # builds the Rust extension via maturin
maturin develop --release           # rebuild after Rust changes
cargo test -p lambroute-native    # Rust unit tests
pytest                              # Python + integration tests (both engines)
ruff check . && mypy                # lint + strict typing
python tests/benchmarks/bench_routing.py
```

## License

MIT

