diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d295fec3..962cb9bb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,7 +17,7 @@ repos: entry: black --config pyproject.toml --check . language: python types: [python] - additional_dependencies: ['black>=24.10.0'] + additional_dependencies: ['black==26.10.1'] pass_filenames: false - id: isort-check @@ -25,7 +25,7 @@ repos: entry: isort --sp pyproject.toml --check-only --diff . language: python types: [python] - additional_dependencies: ['isort>=5.13.2'] + additional_dependencies: ['isort==9.0.1'] pass_filenames: false - id: isort-fix @@ -33,7 +33,7 @@ repos: entry: isort --sp pyproject.toml . language: python types: [python] - additional_dependencies: ['isort>=5.13.2'] + additional_dependencies: ['isort==9.0.1'] pass_filenames: false - id: black-fix @@ -41,7 +41,7 @@ repos: entry: black --config pyproject.toml . language: python types: [python] - additional_dependencies: ['black>=24.10.0'] + additional_dependencies: ['black==26.10.1'] pass_filenames: false - id: mypy @@ -50,12 +50,12 @@ repos: language: python types: [python] additional_dependencies: - - mypy>=1.12.0 - - rich>=13.9.2 - - click>=8.1.7 - - pyyaml>=6.0.0 - - jinja2>=3.1 - - types-PyYAML>=6.0.12 + - mypy==2.3.1 + - rich==15.0.0 + - click==8.3.2 + - pyyaml==6.0.3 + - jinja2==3.1.6 + - types-PyYAML==6.0.12.20260408 pass_filenames: false ci: diff --git a/CHANGELOG.md b/CHANGELOG.md index 7de896ff..3d09cf39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,11 @@ Every template except `fastapi-hello`, the code `fastkit init` generates for its Every 401 carries `WWW-Authenticate`, and each project reads its configuration from one settings module that loads `.env`. -- **Removed templates:** `fastapi-async-crud`, `fastapi-dockerized` and `fastapi-psql-orm` are gone, together with their tutorials. Projects generated from them keep working, and `fastkit doctor` still recognises their example secrets. Use `fastapi-sqlmodel` (async; SQLite, PostgreSQL or MySQL) or `fastapi-default` for new projects. +- **`fastkit init` is guided by default:** it asks for a project name and a level (`hello`, `single-file`, `layered`, `domain`, `production`), the database where the level has one, and whether to customise features. The stack question (`minimal` / `standard` / `full`) is gone; `--interactive` is accepted and has no effect, and `-y` uses the defaults without asking. +- **Without a terminal `init` asks nothing:** pass `--project-name` and options such as `--level`, `--database` and `--feature`, or `--config`. Answers piped to stdin are no longer read. +- **`fastkit init --template ` replaces `startdemo`**, which keeps working as an alias and prints a one-line note. +- **Removed templates:** `fastapi-async-crud`, `fastapi-dockerized`, `fastapi-psql-orm` and `fastapi-empty` are gone, together with the tutorials of the first three; use `fastapi-sqlmodel` (async; SQLite, PostgreSQL or MySQL) or `fastapi-default` for new projects, or `--level single-file` instead of `fastapi-empty`. Projects generated from them keep working, and `fastkit doctor` still recognises their example secrets. +- **`minimal` preset:** it now means `single-module`, so saved configs that name `minimal` or no preset create a `fastapi-single-module` project. - **Secrets outside development:** every template and generated settings module now refuses to start with any `ENVIRONMENT` other than `development` (`staging` or `production`) and a missing, example, or shorter than 32-byte `SECRET_KEY`. In `development` an example key only warns. - **`fastapi-mcp`:** `API_V1_STR` is renamed `API_V1_PREFIX`, and the OpenAPI schema moves to `/openapi.json`. `POST /api/v1/auth/login` is removed (use `POST /api/v1/auth/token`), `/auth/me` becomes `GET /api/v1/users/me`, and `/auth/users` becomes `GET /api/v1/users` (superusers only). `/mcp-routes/*` is replaced by `GET /api/v1/mcp-server`. Only the six item operations are MCP tools. Send the MCP key as `X-MCP-API-Key` (`Authorization: Bearer ` still works) so `Authorization` can carry a user token and write tools work in API-key mode. - **`fastapi-auth-jwt`:** a rejected refresh token returns 400 `{"error": "invalid_grant"}` instead of 401; token responses add `expires_in`; `GET /api/v1/users` returns the page envelope. @@ -31,16 +35,19 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - **`init` Session-based / OAuth2:** `GET /auth/me` moves to `GET /api/v1/users/me`, and logout returns 204. - **`init` FastAPI-Users** needs PostgreSQL, MySQL or SQLite; other database choices are rejected. - **`init` WebSocket:** the connection list moves from `/api/v1/ws/connections` to `/api/v1/connections`; `/ws` is unchanged. -- **CLI:** `startdemo` exits with status 1 when it refuses to run or fails, including an in-place overwrite without a terminal or `--yes`. `addroute` exits with status 1 on errors and refuses route names that are not lower-case ASCII. `deleteproject` exits with status 1 when the project does not exist, is not a fastkit project or cannot be deleted (declining the confirmation still exits 0). `runserver` in a project without `.venv` exits with status 1 unless you choose to continue with the current Python. -- **`init` utilities menu:** CORS and Pagination are no longer offered, because every project includes them; the menu is now 1 = Rate-Limiting, 2 = WebSocket. Saved configs that list them still load. +- **CLI:** `init` and `startdemo` exit with status 1 when they refuse to run or fail, including an in-place overwrite without a terminal or `--yes`; invalid options exit with status 2. `addroute` exits with status 1 on errors and refuses route names that are not lower-case ASCII. `deleteproject` exits with status 1 when the project does not exist, is not a fastkit project or cannot be deleted (declining the confirmation still exits 0). `runserver` in a project without `.venv` exits with status 1 unless you choose to continue with the current Python. +- **`init` utilities:** CORS and Pagination are no longer offered, because every project includes them, and `fastapi-pagination` is no longer installed. Rate-Limiting and WebSocket remain; saved configs that list the removed ones still load. ### CLI - New `fastkit doctor [PATH]` checks a generated project for problems that newer templates fixed: a committed or unignored `.env`, a missing `.env.example`, example secrets, an MCP server without authentication, CORS `*` with credentials, Prometheus set up inside the lifespan, `sqlalchemy` without `greenlet`, CRLF scripts, a missing `.gitattributes`, an old `requires-python`, a pinned pre-commit Python, a commit after `yield`, `SlowAPIMiddleware`, Motor, the old pagination demo router and configuration read outside the settings module. It never prints secret values. - `doctor --fix` shows the diff of the safe fixes and asks once (`--yes` skips the question and is required without a terminal); `--dry-run` / `--diff` only previews. `--format json` is for CI, and `--force` checks projects generated before 1.4.0. Exit status: 0 no problem left, 1 problems remain, 2 doctor could not run. - `fastkit addroute` generates a typed CRUD resource with tests in both layouts (schemas, 201 with `Location`, 204, 404, paginated list) and adds `core/pagination.py` to older projects. The domain layout is chosen when the project has a `domains/` package. New options: `--entity` (class name), `--dry-run` (list files) and `--diff` (show changes). It refuses a route whose files already exist. -- `startdemo -y` also skips the creation prompt. `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. -- `startdemo` checks the template name before it asks anything, suggests close matches and points to `fastkit list-templates`; the internal template path is shown only with `--debug`. +- New `init` options: `--level`, `--database`, `--feature AXIS=VALUE`, `--extra-package`, `--template`, `--in-place`, and `--name` for `--project-name`. `--database` matches its choices in any case. +- Author and email default to `git config user.name` / `user.email`, and the package manager to uv when it is installed, otherwise pip. An empty author is left out of `pyproject.toml` for every package manager (Poetry also leaves out an email without a name). +- `--save-config` works for every `init` run except `--dry-run` and records the level or template; `project_name` is the only required config key, a config can name a `level` or a `template`, and `--project-name`, `--author`, `--author-email` and `--description` override the file's values. +- A prompt that gets 10 invalid answers, or whose input ends, exits with status 1. `startdemo -y` also skips the creation prompt, and `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. +- `init --template` and `startdemo` check the template name before they ask anything, suggest close matches and point to `fastkit list-templates`; the internal template path is shown only with `--debug`. - `runserver` in a project without `.venv` prints the commands that create it for the project's package manager (for PDM, ones that keep the `.venv` inside the project) before offering to continue. If you continue, it runs the uvicorn of the Python that runs fastkit and exits with a clear message if that Python has none. - `addroute` on a real single-file project such as `fastapi-hello` explains how to extend it by hand instead of adding packages. Projects that keep `main.py` at the root with their code in packages are handled as before. - `doctor` passed checks say only what was verified, with no severity, and checks that do not apply to a project (secrets, settings, `.gitattributes`) are skipped. JSON output is unchanged. @@ -48,7 +55,7 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - Projects created with Poetry now get a working virtual environment and install with `poetry install`; fastkit sets `package-mode = false` so Poetry installs the dependencies without packaging the application. Poetry 2 or later is required: with an older Poetry, fastkit stops before creating anything, reports the version it found and explains how to upgrade or choose another package manager. - Projects created with PDM now get their `.venv` inside the project even when PDM is configured with `venv.in_project = false`, and `fastapi-hello` installs with PDM without being built as a package. - `list-templates` lists templates from the simplest to the most involved, in the same order on every operating system. `fastkit --help` has a one-sentence description and a "Start here" section. -- `startdemo` shows the template's runtime dependencies in its dependency table and `--dry-run` list, without comment lines or test tools, and the `--dry-run` file list matches the files that are written. Shell scripts in generated projects (`scripts/*.sh`) are executable. +- `init --template` and `startdemo` show the template's runtime dependencies in the summary and the `--dry-run` list, without comment lines or test tools, and the `--dry-run` file list matches the files that are written. Shell scripts in generated projects (`scripts/*.sh`) are executable. - With `--no-venv`, `init` output no longer depends on which package managers are installed. If the requested package manager is not installed and an environment is being created, fastkit prints a warning and sets the project up for an available one; the project's metadata records the one actually used. - `addroute` sorts generated and inserted imports the way isort (black profile) does, for any route name, including names that differ only by a number, and wraps an over-long inserted import. - `startdemo` and `init` refuse to write through a symbolic link in the target directory and list the links before writing anything. @@ -60,10 +67,9 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - **JWT** generates an OAuth2 password flow: `POST /api/v1/auth/register`, `POST /api/v1/auth/token` and `GET /api/v1/users/me`, with users stored in the selected SQL database or MongoDB (in memory otherwise). - **FastAPI-Users** generates working routes (`/api/v1/auth/jwt/*`, `/api/v1/auth/register`, `/api/v1/users/*`) with tests. - **Session-based:** logout invalidates the session, sessions have an absolute lifetime (`SESSION_ABSOLUTE_MAX_AGE`), and the demo account needs `ENABLE_DEMO_USERS=true` (refused outside development). **OAuth2** requires `OAUTH_REDIRECT_BASE_URL` outside development. -- **CORS and Pagination** are built into every project and no longer offered in the menu; `fastapi-pagination` is no longer installed. - **Rate-Limiting** applies `RATE_LIMIT_DEFAULT` to every route and the stricter `RATE_LIMIT_AUTH` to the auth endpoints, using `limits` instead of slowapi. - **MongoDB** uses PyMongo's async client instead of Motor. The SQL session dependency no longer commits; services commit. -- `classic-layered` and `domain-starter` wire every selected feature into the template's `main.py`. +- The `layered`, `domain` and `production` levels (presets `classic-layered` and `domain-starter`) wire every selected feature into the template's `main.py`. - Generated tests run against in-memory SQLite and do not export telemetry. - **Docker:** the image runs as a non-root user and has a healthcheck, `.dockerignore` is generated, compose points the app at its services, and `.env` is supplied at run time instead of copied into the image. **Loguru** is now configured at startup. - **Dev tools:** test and lint tools (pytest and its plugins, ruff, pre-commit) stay out of runtime dependencies. They go to the dev dependency group and to a new `requirements-dev.txt` that includes `requirements.txt`. Generated Dockerfiles install runtime dependencies only; the Makefile, GitHub Actions workflow and devcontainer install `requirements-dev.txt`. @@ -71,7 +77,7 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f ### Templates -- New `fastapi-hello`: a single `main.py` and its tests, for people who have never written a FastAPI app. `POST /items` stores an item in memory and returns it with an id, and `GET /items/{item_id}` returns it or 404. It has no settings module and no secrets. +- New `fastapi-hello`, the `hello` level: a single `main.py` and its tests, for people who have never written a FastAPI app. `POST /items` stores an item in memory and returns it with an id, and `GET /items/{item_id}` returns it or 404. It has no settings module and no secrets. - `fastapi-sqlmodel` runs on SQLite, PostgreSQL or MySQL, selected by `DATABASE_URL`. Install the `postgresql` or `mysql` driver extra, start a local server with the new docker compose file, and use the migrations, which work on all three. A malformed `DATABASE_URL` is reported without echoing credentials. - `fastapi-mcp`: item reads are public; PUT and PATCH work as specified. - `fastapi-auth-jwt`: login, register and refresh are rate limited (`AUTH_RATE_LIMIT_*`); timestamps are timezone-aware (new migration); `GET /api/v1/users/{user_id}` (superusers only) is added. @@ -79,7 +85,8 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the calculator tool and the conversation store are bounded (`MAX_CONVERSATIONS`, `MAX_MESSAGES_PER_CONVERSATION`), and there are hook points for authentication and rate limiting. - Templates that store items in a JSON file no longer reuse ids, write atomically, and their tests no longer overwrite the shipped data. - Unused dependencies and `setup.cfg` files are removed. Template Dockerfiles run as a non-root user and ship a `.dockerignore`. -- `fastapi-sqlmodel`, `fastapi-auth-jwt` and `fastapi-llm-agent` ship a `requirements-dev.txt` for test and lint tools, and their Docker images no longer contain them. +- Every template ships a `requirements-dev.txt` for test and lint tools and keeps them out of `requirements.txt`, so the Docker images of `fastapi-sqlmodel`, `fastapi-auth-jwt` and `fastapi-llm-agent` no longer contain them. +- Every template except `fastapi-hello` ships the ruff configuration that `init`'s ruff option writes. `fastapi-single-module` projects pass isort and `mypy src`, and `fastapi-custom-response` uses Python 3.12 generic syntax for its response envelope. ### Documentation @@ -93,8 +100,11 @@ Upgrading fastkit does not change an existing project. Run `fastkit doctor` in i 1. **Clients of a regenerated project:** apply the contract changes above (paths under `/api/v1`, `/health`, the list envelope, 204 on delete). 2. **Docker:** new images set `ENVIRONMENT=production` and do not contain `.env`; pass `SECRET_KEY` (at least 32 bytes) and the other settings at run time, e.g. `docker run --env-file .env ...`. 3. **`fastapi-auth-jwt` and `fastapi-sqlmodel` projects that adopt the new template code:** run `alembic upgrade head` for the new migration. -4. **Projects from the removed templates** need no change. To move to PostgreSQL or MySQL with `fastapi-sqlmodel`, set `DATABASE_URL` and install the matching driver extra. -5. **Saved `--config` files** with the CORS or Pagination option still work. +4. **Projects from the removed templates**, including `fastapi-empty` projects, need no change and keep working with `addroute`, `doctor` and `runserver`. To move to PostgreSQL or MySQL with `fastapi-sqlmodel`, set `DATABASE_URL` and install the matching driver extra. +5. **Saved `--config` files** keep working: the CORS and Pagination options are accepted, and a `minimal` preset (or none) creates a `fastapi-single-module` project. +6. **Scripts that pipe answers into `fastkit init`** (or use `--interactive`) need options instead: `fastkit init --project-name api --level layered --database SQLite -y`, or `--config`. +7. **`startdemo` scripts** keep working. To switch, use `fastkit init --template --project-name `; `init` does not ask for author, email or description, so pass `--author`, `--author-email` and `--description`, or let git config fill author and email. +8. **The old stacks** added packages without code. The closest replacements are `--level single-file` for `minimal`, and a level with `--database` and `--feature migrations=Alembic` or `--feature async_tasks=Celery` for `standard` and `full`, which generate the code for those packages. ## v1.5.2 (2026-12-01) diff --git a/README.md b/README.md index 2437dabe..305fd2d0 100644 --- a/README.md +++ b/README.md @@ -28,13 +28,13 @@ This project was inspired by the `SpringBoot initializer` & Python Django's `dja ## Key Features - **โšก Immediate FastAPI project creation** : Super-fast FastAPI workspace & project creation via CLI, inspired by `django-admin` feature of [Python Django](https://github.com/django/django) -- **โœจ Interactive project builder**: Guided step-by-step feature selection for databases, authentication, caching, monitoring, and more with auto-generated code +- **โœจ Guided project builder**: Pick a level from one `main.py` to a production layout, then customise databases, authentication, caching, monitoring, and more with auto-generated code - **๐ŸŽจ Prettier CLI output** : Beautiful CLI experience powered by [rich library](https://github.com/Textualize/rich) - **๐Ÿ“‹ Standards-based FastAPI project templates** : Templates follow Python standards and common FastAPI patterns. - **๐Ÿ” Automated template quality assurance** : Weekly automated testing ensures all templates remain functional and up-to-date - **๐Ÿš€ Multiple project templates** : Choose from various pre-configured templates for different use cases (async CRUD, Docker, PostgreSQL, etc.) - **๐Ÿ“ฆ Multiple package manager support** : Choose your preferred Python package manager (pip, uv, pdm, poetry) for dependency management -- **๐Ÿงพ Reproducible project configs** : Save an interactive session to a `.json` / `.toml` / `.yaml` file and replay it with `fastkit init --config` +- **๐Ÿงพ Reproducible project configs** : Save a project's choices to a `.json` / `.toml` / `.yaml` file and replay it with `fastkit init --config` - **๐Ÿท๏ธ Self-describing projects** : Every generated project records its template, preset, package manager, entrypoint and selected features in a `[tool.fastapi-fastkit]` block that `runserver` and `addroute` read back ## Installation @@ -58,64 +58,49 @@ $ pip install FastAPI-fastkit fastkit init [OPTIONS] ``` > [!TIP] -> Scaffolds an empty FastAPI project, creates a virtual environment, installs dependencies - +> Asks for a project name and a level, then creates the project, sets up a virtual environment and installs the dependencies + +- Levels, each one adds structure to the one above: + - `hello` (default): one `main.py` with three endpoints, in-memory data and tests + - `single-file`: the whole app in one module, with settings and tests + - `layered`: separate layers for routes, CRUD, schemas and core configuration + - `domain`: one package per domain with router, service and repository + - `production`: `domain` plus PostgreSQL, Alembic, JWT, CI and Docker +- Asks only what the options leave open: the project name, the level, the database (levels after `hello`) and whether to customise. The customise step covers authentication, background tasks, caching, monitoring, logging, testing, migrations, utilities, tooling, deployment, package manager and custom packages - Key options: - - `--project-name`, `--author`, `--author-email`, `--description` - - `--package-manager` [pip|uv|pdm|poetry] + - `--project-name` (`--name`), `--level`, `--database` [PostgreSQL|MySQL|MongoDB|Redis|SQLite|None] + - `--feature AXIS=VALUE` (repeatable, e.g. `--feature authentication=JWT`; `fastkit list-features` shows the values) and `--extra-package`, for levels after `hello` + - `--template `: copy a bundled template as it is instead of choosing a level (see below) + - `--author`, `--author-email` (default to `git config user.name` / `user.email`), `--description` + - `--package-manager` [pip|uv|pdm|poetry]: defaults to uv when installed, otherwise pip - `--config `: create the project from a saved config file (`.json` / `.toml`, and `.yaml` when PyYAML is installed) with no prompts - - `--save-config `: with `--interactive`, record the answers for later reuse + - `--save-config `: write the project's configuration to a file for reuse with `--config` + - `--in-place`: write into the current directory instead of a new folder - `--dry-run`: print the files and packages that would be created, write nothing - `--no-venv`: skip virtual environment creation (implies `--no-install`) - `--no-install`: skip dependency installation - - `--yes` / `-y`: skip the "Overwrite these files?" confirmation when deploying in place - - Stack selection: `minimal` | `standard` | `full` (interactive) + - `--yes` / `-y`: use the defaults for every question that has one and create the project without asking; with `--in-place`, also allow overwriting files +- Without a terminal nothing is asked: pass `--project-name` (or `--config`) and everything else takes its default. Exit status: 0 created, previewed or cancelled, 1 refused or failed, 2 invalid options -### Create a project with interactive mode ```console -fastkit init --interactive +fastkit init --project-name api --level domain --database SQLite --feature authentication=JWT --no-venv -y ``` -> [!TIP] -> Guided step-by-step project setup with intelligent feature selection - -- Features: - - **Architecture preset**: `minimal` | `single-module` | `classic-layered` | `domain-starter` (default) - - **Database selection**: PostgreSQL, MySQL, MongoDB, Redis, SQLite - - **Authentication**: JWT, OAuth2, FastAPI-Users, Session-based - - **Background tasks**: Celery, Dramatiq - - **Caching**: Redis, fastapi-cache2 - - **Monitoring**: Loguru, OpenTelemetry, Prometheus - - **Testing**: Basic (pytest), Coverage, Advanced (with faker, factory-boy) - - **Utilities**: Rate-Limiting, WebSocket (CORS and pagination are built into every project) - - **Logging**: structured JSON logging with a request-id middleware - - **Migrations**: Alembic (async env, baseline revision) - - **Tooling**: ruff, pre-commit, GitHub Actions, devcontainer, Makefile (multi-select) - - **Deployment**: Docker, docker-compose with auto-generated configs - - **Package manager**: pip, uv, pdm, poetry - - **Custom packages**: Add your own dependencies -- Auto-generates (varies by preset - see [the matrix](https://bnbong.github.io/FastAPI-fastkit/reference/preset-feature-matrix/) for details): - - `main.py` regenerated from selected features for `minimal` / `single-module`; for `classic-layered` / `domain-starter` the shipped `main.py` is kept and every feature is wired into it - - Database module and authentication package at preset-specific paths, with routes under `/api/v1` - - Docker deployment files (`Dockerfile`, `docker-compose.yml`) with the preset's correct uvicorn entrypoint - - Test configuration (pytest with coverage) - - `GET /health` on every generated project, and `GET /ready` when it has a database or cache - - Real working code with tests โ€” not just installed packages โ€” for background tasks, caching, WebSocket, rate limiting, OpenTelemetry, and JWT, FastAPI-Users, OAuth2 and session-based auth - - `--dry-run` previews the exact file tree a run would create, including logging/migrations/tooling artifacts + +Every generated project serves `GET /health` at the root and mounts its API under `/api/v1`; with a database or cache it also serves `GET /ready`. Selected features come with real working code and tests, not just installed packages. See [the matrix](https://bnbong.github.io/FastAPI-fastkit/reference/preset-feature-matrix/) for where each feature lands per level. ### Create a project from a template ```console -fastkit startdemo [TEMPLATE] [OPTIONS] +fastkit init --template