HTTP
Titancore provides request, upload, and response adapters over FastAPI and Starlette. The HTTP kernel registers the request provider automatically. The host retains body parsing, validation, multipart limits, streaming, and response transport.
Inject a framework request through its plain type annotation.
from titancore.facades import Route
from titancore.foundation.http import inject
from titancore.http import Request, Response
@inject
async def create(request: Request) -> Response:
return Response.json(
{"name": await request.input("name")},
status=201,
).header("X-Application", "example")
Route.post("/items", create)
The request is also available through the Request contract in
titancore.contracts.http. Both keys resolve the same request-scoped
adapter. Controllers and handlers use the framework container's normal
injection declarations.
Request input helpers reuse Arr for nested dot paths.
input(key, default)reads combined query and body fields.all()returns the combined mapping, with body values taking precedence.has(key)checks field presence, including a stored null value.only(keys)andexcept_(keys)select or remove fields.json(key, default)reads JSON through the cached host parser.query(key, default)reads query fields without reading the body.body()reads raw body bytes.
Await helpers that read the body. Query and metadata accessors are
synchronous. input() and all() require an object-shaped JSON body.
json() can return any JSON value. Malformed structured input produces
HTTP 400 with a safe error message.
Query and form mappings retain the last value for a repeated field name. JSON arrays retain their normal structure. Read raw body bytes before parsing form data when both representations are needed.
method(), is_method(name), path(), url(), full_url(),
header(name, default), bearer_token(), and ip() expose host metadata.
Paths omit the surrounding slashes, except that the root path remains
"/". The IP address comes from the host's peer information. Proxy trust
remains host configuration.
When Authenticate() protects a route, request.user() returns the same
account as the Auth facade. Unauthenticated requests return None.
Bearer parsing is shared with the authentication middleware.
Uploads¶
await request.file("document") returns an UploadedFile adapter or None.
It exposes client metadata through get_client_original_name(),
get_client_mime_type(), and get_size(). Treat client metadata as
untrusted input.
Use read(size) and seek(offset) to consume an upload. The request scope
closes parsed files after the ASGI response completes, including streaming
responses. Applications can close an upload earlier with close().
With the filesystem provider registered, store_as uses the configured
storage disk.
from uuid import uuid4
@inject
async def upload(request: Request) -> Response:
document = await request.file("document")
if document is None:
return Response.json({"detail": "Document required."}, status=422)
path = await document.store_as("documents", f"{uuid4().hex}.bin")
return Response.json({"path": path}, status=201)
Route.post("/documents", upload)
Pass a third argument to store_as to select a named disk. Destination
paths follow the filesystem module's root confinement rules. Upload storage
reads the complete file into memory.
Responses¶
Construct Response(content, status, headers) for text or bytes.
Response.json(data, status, headers) uses FastAPI's value conversion and
Starlette's JSON serialization. header(name, value) and
with_headers(mapping) support fluent header updates.
Additional factories delegate directly to the host.
Response.no_content()
Response.redirect("/api/items")
Response.download(app.path("storage", "report.pdf"), filename="report.pdf")
Response.stream(iter([b"hello", b" world"]), media_type="text/plain")
Here app is the application whose trusted paths select the download.
Streams accept synchronous or asynchronous iterables of text or bytes.
Starlette owns file ranges, streaming iteration, and disconnect handling.
Framework routes, included native routers, and direct kernel.asgi routes share
FastAPI's actual request body cache. Host-validated endpoint body arguments
can be combined with framework request input. Application input validation
continues to use the host's supported type declarations and Pydantic models.
Use await request.validate(Schema) to validate combined input with an
application Pydantic model. The kernel returns field errors with status 422.
See validation for the factory, facade, and model
constraints.
Correlation and expected statuses¶
Use titancore.http.middleware.RequestIdMiddleware in route middleware
declarations to attach a server-generated X-Request-ID. Incoming headers
do not choose that value. A domain stream can provide its own response ID,
which the middleware preserves.
Raise titancore.http.exceptions.HttpException(status, detail) for expected
HTTP failures. The HTTP host renders the response; application controllers
do not need to import host exception or middleware types.
Server-sent events¶
ServerSentEvent delegates field validation and wire framing to FastAPI.
EventStreamResponse uses the existing Starlette streaming transport. It
consumes an async generator lazily, adds SSE headers, and closes the generator
when iteration ends, sending fails, or consumption is cancelled.
from collections.abc import AsyncGenerator
from titancore.http import EventStreamResponse, ServerSentEvent
async def events() -> AsyncGenerator[ServerSentEvent, None]:
yield ServerSentEvent(event="completed", data={"ok": True})
response = EventStreamResponse(events())
Use raw_data for text without JSON encoding. FastAPI validates event names,
IDs and retry intervals. Applications own event payloads, authorization and
resource acquisition. Resources acquired by a generator should be released
in its finally block. The response waits for each transport send before it
reads the next event. A proxy or client can still buffer data.
After sending headers, an unhandled source error interrupts the stream. It cannot replace the status or send a new JSON error response. An application can catch an expected error and emit a final event with safe details. The response sets no stream deadline and adds no replay store. Applications own stream deadlines, reconnection replay, and heartbeat scheduling.