Skip to main content

nexus-kit-fastapi

PyPI CI

FastAPI + uvicorn as a nexus-kit lifecycle service, plus a Depends bridge into the nexus container.

A bridge, not a wrapper: FastAPI stays fully in charge of HTTP — routers, middleware, auth, OpenAPI are plain FastAPI. This package owns only the process concerns: when the server starts and stops (as one ServiceInterface among your other services), and how route handlers reach the nexus container.

uv add nexus-kit-fastapi

The server as a service

# app/api/service.py
from injector import inject, singleton
from fastapi import FastAPI
from nexus_kit.interfaces import ContainerInterface
from nexus_kit_fastapi import HttpService

from app.config.environment import Environment
from app.api import health, items

@singleton
class ApiService(HttpService):
    @inject
    def __init__(self, env: Environment, container: ContainerInterface) -> None:
        super().__init__(container)
        self.host, self.port = env.HOST, env.PORT

    def create_app(self) -> FastAPI:          # plain FastAPI — yours entirely
        app = FastAPI(title="my api")
        app.include_router(health.router)
        app.include_router(items.router)
        return app
# app/application.py
class Application(ApplicationInterface):
    SERVICES = [Database, Cache, ApiService]   # http last up, first down

    async def _serve(self) -> None:
        async with ServiceRunner(self._container, self.SERVICES):
            await self._container.get(ApiService).wait()   # until Ctrl+C / SIGTERM

start() returns only once the socket is bound — a busy port raises right there and ServiceRunner rolls the other services back. stop() is a graceful uvicorn shutdown. port = 0 binds an ephemeral port (service.bound_port tells which — handy in tests).

Two defaults differ from bare uvicorn. The access log is off: uvicorn writes every URL with its query string, and tokens or sign-in codes in a URL would land in your logs. The server header is off: it only advertises the stack. Turn either on with access_log = True / server_header = True on your subclass. Both hold even if you override uvicorn_config.

Behind a reverse proxy at a sub-path

Published as https://host/apps/x/ with the proxy stripping the prefix (Traefik stripPrefix, nginx proxy_pass http://app/;)? The app receives /ping for /apps/x/ping and must emit prefixed links back. That is the ASGI root_path, and the bridge exposes it next to host and port:

self.host, self.port, self.root_path = env.HOST, env.PORT, env.URL_PREFIX

URL_PREFIX defaults to "" in your Environment and is set by the deployment (compose environment:, systemd, k8s) — the same class of config as the port, so it never lands in code or templates. Its form is /apps/x: a missing leading slash, a trailing one, or a bare / fails start() with a ValueError naming the fix, instead of breaking links after deploy. Routing stays prefix-free; request.url_for(...), redirects built from it, /docs and /openapi.json generate prefixed URLs on their own. Only absolute paths you write as strings (href="/x", fetch("/api/x"), RedirectResponse("/")) need to go through request.scope["root_path"] instead.

# compose: the prefix lives once, next to the proxy rule that strips it
labels:
  - traefik.http.routers.x.rule=PathPrefix(`/apps/x`)
  - traefik.http.routers.x.middlewares=x-strip
  - traefik.http.middlewares.x-strip.stripprefix.prefixes=/apps/x
environment:
  - HOST=0.0.0.0
  - URL_PREFIX=/apps/x

Routes reach the container through plain Depends

Injected(cls) is an ordinary FastAPI dependency that resolves cls from the container — no per-service get_x() boilerplate:

from nexus_kit_fastapi import Injected

@router.get("/greet")
async def greet(name: str, greeter: Greeter = Injected(Greeter)) -> dict[str, str]:
    return {"message": greeter.greet(name)}

It composes with everything FastAPI: auth dependencies, sub-dependencies, Annotated, middleware. For tests, bind fakes into the container (container.set(Greeter, FakeGreeter())) and drive the app with FastAPI's TestClient — attach the container manually via attach_container(app, container), no server needed.

Signals

The bridge handles SIGINT/SIGTERM (and SIGBREAK on Windows) itself and converts them into a graceful drain: wait() returns, your Application body exits, ServiceRunner stops every service, the process ends normally. A second signal skips the drain and goes down hard.

Why not leave it to uvicorn: uvicorn's stock signal capture restores the previous handlers after its own shutdown and re-raises the captured signal — with default handlers a SIGTERM kills the process before the rest of your services get their stop(). In a composite app that breaks the whole teardown promise, so the bridge disables uvicorn's capture and owns the conversion. Set handle_signals = False on your subclass if the application manages signals itself. The nexus core remains signal-free.

What this package deliberately does NOT do

  • No FastAPI lifespan management — your Application + ServiceRunner own the lifecycle; the HTTP edge is just one service among many.
  • No routing/middleware/auth helpers — that's FastAPI's job.

For AI assistants

The package ships a compact machine-oriented reference — .ai/guide.md: the HttpService contract, the Injected bridge, and the anti-patterns to avoid. Point your agent at it before it touches the HTTP layer.

In a consumer app (nexus-kit 0.5+) this guide is on the kernel's allowlist, so it lands in .nexus-kit/guides/nexus-kit-fastapi.md (indexed by .nexus-kit/map.md, which your AGENTS.md mounts) and your assistant reads it on demand when working on the HTTP layer. See the kernel's README for how you refresh the atlas — it's a command you run, never something your agent is told to run.

License

MIT © Astislav Bozhevolnov

Metadata

Release files for nexus-kit-fastapi 0.4.2

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

Source distribution (sdist)

Source distribution for nexus-kit-fastapi 0.4.2
File Size Uploaded Provenance Actions
nexus_kit_fastapi-0.4.2.tar.gz 19.8 kB Without provenance Details for nexus_kit_fastapi-0.4.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nexus-kit-fastapi 0.4.2
File Interpreter ABI Platform Actions
nexus_kit_fastapi-0.4.2-py3-none-any.whl Python 3 none any Details for nexus_kit_fastapi-0.4.2-py3-none-any.whl

Total release size: 34.9 kB

Release files / nexus_kit_fastapi-0.4.2.tar.gz

Download URL nexus_kit_fastapi-0.4.2.tar.gz
Size 19.8 kB
Tags Source
SHA-256 checksum
How to use checksums
7a69c76f00f4f09cd6faa4f5c751db551e2278fbf727f2c9a5f60e9a6825df5a
BLAKE2b-256 checksum
How to use checksums
a30885688f9a4139b3a026e64772cc9269a12ceba62f5fc02b5c8e330c9b6013
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / nexus_kit_fastapi-0.4.2-py3-none-any.whl

Download URL nexus_kit_fastapi-0.4.2-py3-none-any.whl
Size 15.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cf9e02de0d32e6fb480e4c5817601c6e22c228689808b31d8152e87b8b058ea2
BLAKE2b-256 checksum
How to use checksums
bebb1331cd5d6580ddacbb69ed729ca652c029a4e288c338e1513238463e1828
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for nexus-kit-fastapi 0.4.2

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