How fastapi/fastapi-cli works
Project type and purpose
• This is a command-line interface (CLI) tool for discovering and running FastAPI applications.
• It provides two main commands: fastapi dev (development server with auto-reload) and fastapi run (production server).
File structure
• src/fastapi_cli/: the production code.
• __main__.py – entry point when you run fastapi.
• cli.py – command parsing and dispatch (dev, run).
• discover.py – logic to scan the filesystem, detect FastAPI app modules, and build import strings (e.g., main:app).
• logging.py – sets up and centralizes CLI logging.
• exceptions.py – custom exceptions for discovery and runtime errors.
• utils/cli.py – shared helper functions for argument normalization, path resolution, default values.
• scripts/: developer utilities for linting, formatting, and testing.
• tests/: unit and integration tests covering discovery, CLI behavior, and configuration edge cases.
• .github/: CI/CD workflows, issue templates, and Dependabot configuration.
• pyproject.toml, **requirements*.txt, pdm_build.py**: build and dependency definitions.
README for architecture hints
• FastAPI CLI uses Uvicorn under the hood to launch the ASGI server.
• Discovery: automatically finds the FastAPI app object in user code.
• Logs: prints structured logs (INFO, server messages, tips).
1. User / Terminal – the actor invoking fastapi dev or fastapi run.
2. CLI Entry Point (__main__.py)
3. Argument Parser (cli.py)
4. Discovery Engine (discover.py)
5. Configuration & Utils (utils/cli.py, logging.py)
6. Uvicorn Server (external library)
7. User Application (the FastAPI app module discovered on disk)
8. File System – where the user’s code resides
9. Network Interface – HTTP endpoints served by Uvicorn
1. Terminal → CLI Entry Point: user invokes command.
2. CLI Entry Point → Argument Parser: parse sub-commands & flags.
3. Argument Parser → Discovery Engine: supply target path(s).
4. Discovery Engine ↔ File System: scan directories, locate app object, handle exceptions.
5. Discovery Engine → CLI: returns import string (e.g., main:app).
6. CLI → Uvicorn: call uvicorn.run(import_string, host, port, reload) with appropriate flags.
7. Uvicorn ↔ User Application: import and serve the ASGI app.
8. Uvicorn → Network Interface: listens on TCP socket.
9. Logging flows from CLI & Uvicorn → Terminal.
c. Architectural patterns and principles
• Separation of Concerns: CLI parsing, discovery, logging, and server launch are modularized.
• Dependency Injection: Uvicorn configuration is passed in, not hard-coded.
• Resilience: custom exceptions in discovery to provide clear user feedback.
d. Key technologies and libraries
• Python 3.8+
• FastAPI CLI (this project)
• Uvicorn (ASGI server)
• Click or argparse (depending on implementation in cli.py)
• WatchFiles (for auto-reload)
• External libraries/services in another (e.g., green).
• User code and filesystem in a third (e.g., yellow).
• Rectangles for internal modules,