fastapi-oneshot
Run a one-shot Python script against an existing FastAPI app, so that the script's main function receives the app's dependencies — DB sessions, settings, clients — through ordinary Depends.
fastapi-oneshot registers main as a temporary path operation, enters the app's lifespan, and sends a single in-process request to it through httpx.ASGITransport. Dependency resolution, yield cleanup, dependency_overrides and the lifespan all work exactly as they do for a request handler, and everything runs on one event loop in the main thread.
Installation
Install fastapi-oneshot into the same environment as your app, because it imports the app:
uv add --dev fastapi-oneshot
or
pip install fastapi-oneshot
Python 3.10 or later and FastAPI 0.115.0 or later (below 1.0) are required.
Usage
fastapi-oneshot SCRIPT --app MODULE:ATTR [-- SCRIPT_ARG ...]
| Argument | Meaning |
|---|---|
SCRIPT |
Path to the script file that defines main. |
--app MODULE:ATTR |
Import string of the FastAPI instance, e.g. myapp.main:app. |
-- |
Everything after the first -- is passed to the script verbatim. |
Run the command from your project root: the current working directory is put on sys.path before --app is imported, as with uvicorn and fastapi run.
Writing a script
A script is a Python file that defines a module-level function named main, with def or async def. Every parameter of main is a dependency, declared with Depends(...) exactly as in a path operation:
# scripts/backfill.py
import argparse
import sqlite3
from typing import Annotated
from fastapi import Depends
from fastapi_oneshot import get_argv
from myapp.dependencies import get_db
def main(
db: Annotated[sqlite3.Connection, Depends(get_db)],
argv: Annotated[list[str], Depends(get_argv)],
) -> None:
parser = argparse.ArgumentParser(prog="backfill")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args(argv)
...
fastapi-oneshot scripts/backfill.py --app myapp.main:app -- --dry-run
- The app's lifespan runs around
main, so dependencies can read lifespan-initialized state throughrequest.app.stateand lifespan-yielded state throughrequest.state. - A sync
mainruns in FastAPI's threadpool; an asyncmainruns on the main-thread event loop shared with the lifespan. - The return value of
mainis discarded. Signal failure by raising an exception. - The script's directory is put on
sys.path, so the script can import sibling modules, as withpython script.py. - The script runs as a module named
__oneshot_script__, so anif __name__ == "__main__":block does not run.
Script arguments: get_argv
fastapi_oneshot.get_argv is a dependency that returns the arguments after -- as list[str] ([] when there is no --). Parse them with argparse or any other parser, as in the example above.
Script options always come from get_argv. A plain parameter of main that is not a dependency is not a CLI option: a plain parameter with a default (verbose: bool = False) always receives its default, and a required plain parameter fails the run with a 422 validation error.
Calling get_argv outside a fastapi-oneshot run, e.g. from a normal app route, raises RuntimeError.
Overriding dependencies
The request that runs main carries no headers, cookies, query or body. Override every dependency that reads them — such as "current user from a bearer token" — with app.dependency_overrides at module level in the script:
from myapp.auth import get_current_user
from myapp.main import app
from myapp.models import User
app.dependency_overrides[get_current_user] = lambda: User(id=0, name="oneshot")
The same applies to app-level dependencies given to FastAPI(dependencies=[...]), such as a global authentication check: they run before main, so override them in the script.
Import the app through the same module path as --app (from myapp.main import app for --app myapp.main:app). Importing it through another path, such as src.myapp.main, creates a second app instance, and the override applies to that instance instead of the one that runs. Set overrides at module level: overrides set inside main are too late to affect main's own parameters.
Exit codes
| Outcome | Exit code |
|---|---|
main returns and the response is 2xx |
0 |
An exception is raised in main, a dependency, the lifespan, the app import or the script import (the traceback is printed) |
1 |
The response is not 2xx — e.g. HTTPException, a 422 validation error, a rejecting app-level dependency or middleware |
1 |
main raises SystemExit (e.g. sys.exit(3), argparse errors) |
the requested status |
The script or --app cannot be loaded, or main is missing or not a plain function |
2 |
Missing SCRIPT or --app |
2 |
A non-2xx response is reported on stderr with its status and body:
fastapi-oneshot: request failed with status 401
{"detail":"missing Authorization"}
Once the lifespan has started, it is shut down normally before fastapi-oneshot exits, whatever the outcome.
Known limitations
- Middleware runs. Every app middleware processes the request, which is sent to
http://localhost/__fastapi_oneshot__. A middleware that rejects it (e.g. authentication,TrustedHostMiddlewarewithoutlocalhostinallowed_hosts,HTTPSRedirectMiddlewareanswering 307 — redirects are not followed) results in a non-2xx exit. - App-level dependencies run. Dependencies given to
FastAPI(dependencies=[...])apply to the oneshot route, so a global authentication or rate-limit dependency runs beforemainand typically rejects the request (401/403 → exit 1). Override such a dependency in the script withapp.dependency_overrides. Dependencies attached to anAPIRouterdo not apply, because the route is added to the app directly. - Request-derived dependencies. The request carries no headers, cookies, query or body beyond httpx defaults; dependencies that read them must be overridden in the script.
- Lifespan entered directly. The lifespan runs through
app.router.lifespan_context(app), not through an ASGIlifespanscope, so ASGI middleware that intercepts thelifespanscope does not see startup and shutdown. - Ctrl-C.
fastapi-oneshotinstalls no signal handling of its own. On Python 3.11+, the first Ctrl-C cancels the run:CancelledErroris raised at the currentawait, propagates throughyield-dependency cleanup and into the lifespan, and the process ends withKeyboardInterrupt; a second Ctrl-C raisesKeyboardInterruptimmediately. On Python 3.10,KeyboardInterruptis raised wherever the main thread is, and the run is cancelled the same way. Lifespan shutdown code runs on this path only when it is intry/finally. A syncmainrunning in a worker thread cannot be interrupted, and the process exits only after it returns. The exit status is Python's default for an uncaughtKeyboardInterrupt(130 in POSIX shells). Make scripts that must stay consistent when interrupted rely on DB transactions. sys.exit()inmainis a failed request to the app.sys.exit(...)— includingsys.exit(0)andargparse's--help— travels through the app as an exception: it is thrown intoyielddependencies at theiryield(post-yieldsuccess code such asdb.commit()is skipped andexcept Exceptionrollback branches run) and reaches the app'sException/ 500 handler and error-reporting middleware as a server error. The process still exits with the requested status. End a successful run by returning frommain; usesys.exitonly for usage errors and failures.SystemExitraised by a dependency rather than bymainis unsupported: lifespan shutdown is then best-effort, as on Ctrl-C.
License
MIT
Metadata
Release files for fastapi-oneshot 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_oneshot-0.1.0.tar.gz | 40.3 kB | Without provenance | Details for fastapi_oneshot-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_oneshot-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for fastapi_oneshot-0.1.0-py3-none-any.whl |
Total release size: 48.6 kB
Release files / fastapi_oneshot-0.1.0.tar.gz
| Download URL | fastapi_oneshot-0.1.0.tar.gz |
|---|---|
| Size | 40.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d693ef42bc5900b9624d3a488034f8a844bd474fb5bfa3dcf44267c887e2e69e
|
|
BLAKE2b-256 checksum How to use checksums |
de00160c10df4c4659766c569bb18e00d86939727e9274ce17981b0d98ccdfd6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / fastapi_oneshot-0.1.0-py3-none-any.whl
| Download URL | fastapi_oneshot-0.1.0-py3-none-any.whl |
|---|---|
| Size | 8.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d26d11e15e75fed9e33d8be6ee762aef9dcd1ef8706475455aed11a185b6550d
|
|
BLAKE2b-256 checksum How to use checksums |
68c983aeb413857ca88c0021eeee58b2d73dd483bc89f83e12bdf9f85895fc45
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for fastapi-oneshot 0.1.0
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.