# Key Components

The primary public API pieces you work with when building a Flasgo app.

Source: https://flasgo.dev/reference/key-components/

## Application class

`Flasgo` is the core application object. It owns HTTP and WebSocket routing, route-aware CORS, lifespan, process state, middleware, settings, templates, static assets, testing, optional internal endpoints, and the development server entrypoint.

Common methods include:

- `route`, `get`, `post`, `put`, `patch`, `delete`
- `websocket`, `add_websocket_route`, `lifespan`, `state`
- `before_request`, `after_request`, `errorhandler`
- `register_auth_backend`, `authorize`
- `ratelimit`, `resolve_outbound_url`, `aresolve_outbound_url`
- `configure_templates`, `render_template`, `render_template_async`
- `configure_static`, `test_client`
- `openapi_spec`, `run`
- `register_blueprint`, `url_for`, `policy_snapshot`, `override_dependencies`

## Request and response primitives

| Component | Role |
| --- | --- |
| `Request` | Access method, path, headers, query params, JSON, and form data |
| `Response` | Build explicit HTTP responses with case-insensitive headers, validated cookies, redirects, JSON, and templated output |
| `FormData` | Read parsed form values and uploaded files |
| `UploadedFile` | Represents an uploaded file from multipart form handling |
| `Body`, `Query`, `Header`, `Cookie`, `Form` | Bind and validate typed request data through `Annotated` |
| `Depends` | Resolves and caches returned or yielded provider values with request/function lifetimes |
| `ValidationIssue` | Describes one bounded request validation failure |
| `RequestValidationError` | Carries structured request binding failures |
| `FormValidationError` | Adds parsed `FormData` for explicit form redisplay handling |
| `HTTPException` | Raises an HTTP error with an explicit status, detail, and optional headers |
| `WebSocket` | Accepts, receives, sends, iterates, denies, and closes WebSocket connections |
| `WebSocketDisconnect` | Reports a peer disconnect and its close code |
| `BackgroundTasks` | Runs best-effort tasks after complete response delivery and request dependency cleanup |

## Globals and helpers

Flasgo exposes a few framework conveniences for request-time access:

| Helper | Purpose |
| --- | --- |
| `request` | Access the current request |
| `session` | Access the current session mapping from the configured backend |
| `url_for` | Generate validated URLs using the active request application and mount path |
| `current_user` | Access the authenticated user context |
| `jsonify` | Return JSON from lightweight handlers |
| `redirect` | Create redirect responses quickly |
| `is_safe_redirect_target` | Vet request-controlled relative same-origin redirect destinations |
| `abort` | Raise structured HTTP errors; annotated `-> Never` for type checkers |

## Authentication and authorization

| Component | Role |
| --- | --- |
| `User` and `AuthResult` | Carry the authenticated identity and optional challenge |
| `bearer_token_backend` | Adapts a sync or async token validator into an auth backend |
| `extract_bearer_token` | Strictly extracts a configured bearer scheme |
| `jwt_backend` | Builds a strict optional HS256 authentication backend |
| `encode_jwt` | Creates a short-lived token matching that backend contract |
| `AllowAny` | Allows anonymous and authenticated users |
| `IsAuthenticated` | Requires an authenticated user |
| `HasScope` | Requires one named user scope |

Custom permission objects and sync or async permission callables are also supported.

## Routing style

Flasgo uses Flask-style decorators and path converters.

```python
from flasgo import Flasgo

app = Flasgo()


@app.get("/posts/<int:post_id>")
async def show_post(post_id: int):
    return {"post_id": post_id}
```

Supported converter patterns include `<name>`, `<int:name>`, `<float:name>`, and `<path:name>`. An untyped `<name>` segment is converted to the handler's annotated type. Pass HTTP methods as a collection such as `methods=["POST"]`; a single string raises `TypeError`. Repeated parameter names, unknown converters, malformed placeholders such as `<int: id>`, and duplicate explicit route names raise `ValueError` at registration.

## Supporting subsystems

| Subsystem | Role |
| --- | --- |
| `Settings` | Loads known configuration from mappings, modules, objects, or a `Settings` instance |
| `CORSConfig` | Defines an exact-origin application or per-route browser access policy |
| `SessionSigner` | Signs client-side session cookies with HMAC-SHA256 |
| `SSRFGuard` | Validates outbound URLs, blocks private networks by default, and pins resolved addresses |
| `RateLimiter` | Applies in-process sliding-window limits for security failures or route-level quotas |
| `JinjaTemplates` | Renders templates through a sandboxed Jinja environment; `render_async()` serves templates configured with `enable_async=True` |
| `TestClient` | Exercises HTTP, cookies, forms, files, lifespan, and WebSockets without a network socket |
| `configure_logging` | Configures bounded text or JSON events for the `flasgo` logger hierarchy |
| `flasgo[metrics]` subsystem | Records optional per-process Prometheus metrics behind bearer authentication |
| `app.metrics_registry` | Read-only access to the app-local Prometheus registry, or `None` when metrics are disabled (0.9.1+) |
| `flasgo[otel]` subsystem | Traces HTTP and WebSocket work and exports through OTLP/HTTP |
| `Flasgo.openapi_spec` | Generates OpenAPI 3.2 data with JSON Schema 2020-12 |

Route-level rate limits are attached with `app.ratelimit(...)` or the exported `rate_limit` decorator. The built-in security-failure limiter is separate and handles repeated host, CSRF, and authentication/authorization failures, including protected docs and metrics endpoints.

## Route composition, streaming, and shared storage

Flasgo 0.9.0 provides these additional exports and methods:

| Component | Role |
| --- | --- |
| `Blueprint` | Nested HTTP route groups with additive permissions, dependencies, and quotas |
| `ResponseValidationError` | Safe server-side failure when an explicit response contract is violated |
| `StreamingResponse` | Bounded async bytes/text with transport backpressure and disconnect cleanup |
| `EventSourceResponse`, `ServerSentEvent` | JSON-encoded SSE data, validated event metadata, and heartbeats |
| `NDJSONResponse` | Bounded JSON values emitted one per line |
| `RedisStore` | Async Redis/Valkey storage with bounded operations and atomic updates |
| `RedisRateLimiter` | Shared sliding-window quotas for decorated HTTP/WebSocket routes |
| `ServerSideSessions` | Opaque-cookie sessions with rotation, revocation, and stale-write detection |
| `MemoryStore` | Bounded process-local session storage for tests and development |
| `StoreUnavailable` | Backend availability failure, handled as `503` by the framework |
| `Session.regenerate`, `Session.session_id` | Request rotation on save and read the current server-side identifier |
| `TestClient.astream`, `AsyncTestStream` | Read HTTP streams incrementally in an async test context |

See the [0.9.0 feature overview](/overview/#flasgo-090-additions) for installation and focused guides. `Session.session_id` is a credential and must not be logged or exposed in responses.

## CLI

The `flasgo` command exposes `run`, `routes`, `openapi`, `check`, and optional Alembic-backed `db` commands. See [CLI and Migrations](/guides/cli-and-migrations/) for examples.

## Supporting public types

The package also exports the types needed for extension and precise testing:

- `Settings` and `Session`
- `RateLimitRule`
- `SSRFConfig`, `SSRFGuard`, `SSRFResolvedURL`, and `SSRFViolation`
- `CORSConfig` and `is_safe_redirect_target`
- `WebSocketException`, `WebSocketHandshakeError`, `SyncWebSocketSession`, and `AsyncWebSocketSession`
- `TestResponse` and `AsyncTestStream`
- `FlasgoJSONFormatter`
- `Body`, `Query`, `Header`, `Cookie`, `Form`, and `Depends`
- `ValidationIssue`, `RequestValidationError`, and `FormValidationError`
- `BaseLoader`, `SecureTemplateLoader`, `Template`, and `TemplateNotFound`
- `create_template_environment` and standalone `render_template`

Sources:

- [README.md](https://github.com/L1ghtn1ng/flasgo/blob/main/README.md)
- [`flasgo/__init__.py`](https://github.com/L1ghtn1ng/flasgo/blob/main/flasgo/__init__.py)
