* ⬆️ Update Sentry and FastAPI
* 🎨 Auto format and update with pre-commit
---------
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
description: Use Library Skills to discover, install, refresh, repair, check, and manage agent skills from installed packages.
---
# Library Skills
Use this skill when a project might benefit from agent skills bundled by its installed packages, or when existing Library Skills-managed symlinks are stale, broken, orphaned, or need to be checked.
Run commands from the project root.
Agents bundle their own skills by including an `.agents/skills` directory. More details in [Library Skills](https://library-skills.io).
## First-Time Setup
- Make sure project dependencies are installed first, for example with `uv sync` for Python projects or `npm install` / `bun install` for Node.js projects.
- Run `uvx library-skills` or `npx library-skills` to discover skills bundled by the installed packages and install selected skills interactively.
- Use `uvx library-skills --all` or `npx library-skills --all` only when all newly discovered skills should be installed without selecting individual skills.
- Use `uvx library-skills --tool-skill` or `npx library-skills --tool-skill` to copy this Library Skills tool skill into the project so future agents know how to discover, install, update, repair, and check skills.
## Commands
- Run `uvx library-skills` or `npx library-skills` to discover package-provided skills, install selected new skills, and reconcile existing managed symlinks.
- Run `uvx library-skills list` or `npx library-skills list` to inspect discovered and installed skills.
- Run `uvx library-skills list --json` or `npx library-skills list --json` for machine-readable installed status.
- Run `uvx library-skills scan --json` or `npx library-skills scan --json` for discovery-only automation.
- Run `uvx library-skills --check` or `npx library-skills --check` to validate managed skill symlink state without changing files.
- Run `uvx library-skills --yes` or `npx library-skills --yes` to repair stale managed symlinks and remove orphaned managed symlinks non-interactively.
- Add `--claude` when `.claude/skills` should also be managed.
- Add `--skill NAME` to install a specific discovered skill by name.
## Safety
- Prefer rerunning `library-skills` over editing managed symlinks manually.
- If installed skill symlinks are broken, dependencies may not be installed yet. Try the project's normal install command first, such as `uv sync`, `npm install`, or `bun install`, then rerun `library-skills`.
- Do not delete or overwrite hand-authored skill directories.
- Library Skills only removes managed symlinks. It should not remove copied or hand-authored skill directories.
description: Use Library Skills to discover, install, refresh, repair, check, and manage agent skills from installed packages.
---
# Library Skills
Use this skill when a project might benefit from agent skills bundled by its installed packages, or when existing Library Skills-managed symlinks are stale, broken, orphaned, or need to be checked.
Run commands from the project root.
Agents bundle their own skills by including an `.agents/skills` directory. More details in [Library Skills](https://library-skills.io).
## First-Time Setup
- Make sure project dependencies are installed first, for example with `uv sync` for Python projects or `npm install` / `bun install` for Node.js projects.
- Run `uvx library-skills` or `npx library-skills` to discover skills bundled by the installed packages and install selected skills interactively.
- Use `uvx library-skills --all` or `npx library-skills --all` only when all newly discovered skills should be installed without selecting individual skills.
- Use `uvx library-skills --tool-skill` or `npx library-skills --tool-skill` to copy this Library Skills tool skill into the project so future agents know how to discover, install, update, repair, and check skills.
## Commands
- Run `uvx library-skills` or `npx library-skills` to discover package-provided skills, install selected new skills, and reconcile existing managed symlinks.
- Run `uvx library-skills list` or `npx library-skills list` to inspect discovered and installed skills.
- Run `uvx library-skills list --json` or `npx library-skills list --json` for machine-readable installed status.
- Run `uvx library-skills scan --json` or `npx library-skills scan --json` for discovery-only automation.
- Run `uvx library-skills --check` or `npx library-skills --check` to validate managed skill symlink state without changing files.
- Run `uvx library-skills --yes` or `npx library-skills --yes` to repair stale managed symlinks and remove orphaned managed symlinks non-interactively.
- Add `--claude` when `.claude/skills` should also be managed.
- Add `--skill NAME` to install a specific discovered skill by name.
## Safety
- Prefer rerunning `library-skills` over editing managed symlinks manually.
- If installed skill symlinks are broken, dependencies may not be installed yet. Try the project's normal install command first, such as `uv sync`, `npm install`, or `bun install`, then rerun `library-skills`.
- Do not delete or overwrite hand-authored skill directories.
- Library Skills only removes managed symlinks. It should not remove copied or hand-authored skill directories.
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions.
All that, on top of all the incredible help provided by a bunch of community members, that give a lot of their time to come here and help others.
That's a lot of work, but if more users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many questions, I'll have to discard and close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
- type:checkboxes
id:checks
attributes:
label:First Check
description:Please confirm and check all the following options.
options:
- label:I added a very descriptive title here.
required:true
- label:I used the GitHub search to find a similar question and didn't find it.
required:true
- label:I searched in the documentation/README.
required:true
- label:I already searched in Google "How to do X" and didn't find any information.
required:true
- label:I already read and followed all the tutorial in the docs/README and didn't find an answer.
required:true
- type:checkboxes
id:help
attributes:
label:Commit to Help
description:|
After submitting this, I commit to one of:
* Read open questions until I find 2 where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
options:
- label:I commit to help with one of those options 👆
required:true
- type:textarea
id:example
attributes:
label:Example Code
description:|
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
placeholder:|
Write your example code here.
render:Text
validations:
required:true
- type:textarea
id:description
attributes:
label:Description
description:|
What is the problem, question, or error?
Write a short description telling me what you are doing, what you expect to happen, and what is currently happening.
placeholder:|
* Open the browser and call the endpoint `/`.
* It returns a JSON with `{"message": "Hello World"}`.
* But I expected it to return `{"message": "Hello Morty"}`.
validations:
required:true
- type:dropdown
id:os
attributes:
label:Operating System
description:What operating system are you on?
multiple:true
options:
- Linux
- Windows
- macOS
- Other
validations:
required:true
- type:textarea
id:os-details
attributes:
label:Operating System Details
description:You can add more details about your operating system here, in particular if you chose "Other".
validations:
required:true
- type:input
id:python-version
attributes:
label:Python Version
description:|
What Python version are you using?
You can find the Python version with:
```bash
python --version
```
validations:
required:true
- type:textarea
id:context
attributes:
label:Additional Context
description:Add any additional context information or screenshots you think are useful.
about:To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
description:You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇
body:
- type:markdown
attributes:
value:|
Thanks for your interest in this project! 🚀
If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/full-stack-fastapi-template/discussions/categories/questions) instead.
- type:checkboxes
id:privileged
attributes:
label:Privileged issue
description:Confirm that you are allowed to create an issue here.
options:
- label:I'm @tiangolo or he asked me directly to create an issue here.
body: `This PR modifies dependency files (\`pyproject.toml\` or \`uv.lock\`), which is restricted to members of the **${context.repo.owner}** organization on GitHub.\n\nIf you need a dependency change, please [open a discussion](https://github.com/${context.repo.owner}/${context.repo.repo}/discussions/new) describing what you need and why.\n\nClosing this PR automatically.`
});
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.payload.pull_request.number,
state: 'closed'
});
core.setFailed('Dependency changes are restricted to organization members.');
} else {
console.log(`Author ${author} (author_association=${assoc}) is allowed to make dependency changes.`);
"message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
},
"waiting": {
"delay": 2628000,
"message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
},
"invalid": {
"delay": 0,
"message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details."
Thank you for your interest in contributing to the Full Stack FastAPI Template! 🙇
## Discussions First
For **big changes** (new features, architectural changes, significant refactoring), please start by opening a [GitHub Discussion](https://github.com/fastapi/full-stack-fastapi-template/discussions) first. This allows the community and maintainers to provide feedback on the approach before you invest significant time in implementation.
For small, straightforward changes, you can go directly to a Pull Request without starting a discussion first. This includes:
- Typos and grammatical fixes
- Small reproducible bug fixes
- Fixing lint warnings or type errors
- Minor code improvements (e.g., removing unused code)
Note that PRs from non-team members are not allowed to modify `pyproject.toml` or `uv.lock`, to prevent supply chain risk.
If you would like to add a new dependency, create a new [Discussion](https://github.com/fastapi/full-stack-fastapi-template/discussions) to explain why.
## Developing
For detailed instructions on setting up your development environment, running the stack, linting, pre-commit hooks, and more, see the [Development Guide](development.md).
## Pull Requests
When submitting a pull request:
1. Make sure all tests pass before submitting.
2. Keep PRs focused on a single change.
3. Update tests if you're changing functionality.
4. Reference any related issues in your PR description.
## Automated Code and AI
You are encouraged to use all the tools you want to do your work and contribute as efficiently as possible, this includes AI (LLM) tools, etc. Nevertheless, contributions should have meaningful human intervention, judgement, context, etc.
If the **human effort** put in a PR, e.g. writing LLM prompts, is **less** than the **effort we would need to put** to **review it**, please **don't** submit the PR.
Think of it this way: we can already write LLM prompts or run automated tools ourselves, and that would be faster than reviewing external PRs.
### Closing Automated and AI PRs
If we see PRs that seem AI generated or automated in similar ways, we'll flag them and close them.
The same applies to comments and descriptions, please don't copy paste the content generated by an LLM.
### Human Effort Denial of Service
Using automated tools and AI to submit PRs or comments that we have to carefully review and handle would be the equivalent of a [Denial-of-service attack](https://en.wikipedia.org/wiki/Denial-of-service_attack) on our human effort.
It would be very little effort from the person submitting the PR (an LLM prompt) that generates a large amount of effort on our side (carefully reviewing code).
Please don't do that.
We'll need to block accounts that spam us with repeated automated PRs or comments.
### Use Tools Wisely
As Uncle Ben said:
> With great ~~power~~ **tools** comes great responsibility.
Avoid inadvertently doing harm.
You have amazing tools at hand, use them wisely to help effectively.
## Questions?
If you have questions about contributing, feel free to open a [GitHub Discussion](https://github.com/fastapi/full-stack-fastapi-template/discussions).
If you have `pipx` and you didn't install `copier`, you can run it directly:
```bash
pipx run copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust
```
**Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/fastapi/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files.
### Input Variables
Copier will ask you for some data, you might want to have at hand before generating the project.
But don't worry, you can just update any of that in the `.env` files afterwards.
The input variables, with their default values (some auto generated) are:
-`project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env).
-`stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels and project name (no spaces, no periods) (in .env).
-`secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above.
-`first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env).
-`first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env).
-`smtp_host`: (default: "") The SMTP server host to send emails, you can set it later in .env.
-`smtp_user`: (default: "") The SMTP server user to send emails, you can set it later in .env.
-`smtp_password`: (default: "") The SMTP server password to send emails, you can set it later in .env.
-`emails_from_email`: (default: `"info@example.com"`) The email account to send emails from, you can set it later in .env.
-`postgres_password`: (default: `"changethis"`) The password for the PostgreSQL database, stored in .env, you can generate one with the method above.
-`sentry_dsn`: (default: "") The DSN for Sentry, if you are using it, you can set it later in .env.
Security is very important for this project and its community. 🔒
Learn more about it below. 👇
## Versions
The latest version or release is supported.
You are encouraged to write tests for your application and update your versions frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
## Reporting a Vulnerability
If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue.
I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you.
## Public Discussions
Please restrain from publicly discussing a potential security vulnerability. 🙊
It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible.
* [uv](https://docs.astral.sh/uv/) for Python package and environment management.
## Docker Compose
## Local Development
Start the local development environment with Docker Compose following the guide in [../development.md](../development.md).
Run the backend locally and connect it to PostgreSQL in Docker Compose.
## General Workflow
From the project root, start PostgreSQL and Mailcatcher:
By default, the dependencies are managed with [uv](https://docs.astral.sh/uv/), go there and install it.
```console
$ docker compose up -d db mailcatcher
```
From `./backend/` you can install all the dependencies with:
Then, from `./backend/`, install the dependencies, prepare the database, and start the development server:
```console
$ uv sync
$ uv run bash scripts/prestart.sh
$ uv run fastapi dev
```
Then you can activate the virtual environment with:
The API is available at `http://localhost:8000`, with automatic interactive docs at `http://localhost:8000/docs`.
```console
$source .venv/bin/activate
```
## General Workflow
Make sure your editor is using the correct Python virtual environment, with the interpreter at `backend/.venv/bin/python`.
Run backend commands from `./backend/` with `uv run`. Make sure your editor uses the Python interpreter at `.venv/bin/python` in the project root.
Modify or add SQLModel models for data and SQL tables in `./backend/app/models.py`, API endpoints in `./backend/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/crud.py`.
@@ -35,69 +37,36 @@ There are already configurations in place to run the backend through the VS Code
The setup is also already configured so you can run the tests through the VS Code Python tests tab.
## Docker Compose Override
## Full Stack with Docker Compose
During development, you can change Docker Compose settings that will only affect the local developmentenvironment in the file `docker-compose.override.yml`.
The changes to that file only affect the local development environment, not the production environment. So, you can add "temporary" changes that help the development workflow.
For example, the directory with the backend code is synchronized in the Docker container, copying the code you change live to the directory inside the container. That allows you to test your changes right away, without having to build the Docker image again. It should only be done during development, for production, you should build the Docker image with a recent version of the backend code. But during development, it allows you to iterate very fast.
There is also a command override that runs `fastapi run --reload` instead of the default `fastapi run`. It starts a single server process (instead of multiple, as would be for production) and reloads the process whenever the code changes. Have in mind that if you have a syntax error and save the Python file, it will break and exit, and the container will stop. After that, you can restart the container by fixing the error and running again:
To run the backend and built frontend in Docker Compose:
```console
$ docker compose run --rm backend bash scripts/prestart.sh
$ docker compose watch
```
There is also a commented out `command` override, you can uncomment it and comment the default one. It makes the backend container run a process that does "nothing", but keeps the container alive. That allows you to get inside your running container and execute commands inside, for example a Python interpreter to test installed dependencies, or start the development server that reloads when it detects changes.
The application is available at `http://localhost:8000`.
To get inside the container with a `bash` session you can start the stack with:
### Docker Compose Override
```console
$ docker compose watch
```
The `compose.override.yml` file contains local settings for published ports, source synchronization, automatic image rebuilds, and backend reloads. Docker Compose applies it automatically when you run `docker compose` without an explicit file list.
and then in another terminal, `exec` inside the running container:
To open a shell in the backend container:
```console
$ docker compose exec backend bash
```
You should see an output like:
```console
root@7f2607af31c3:/app#
```
that means that you are in a `bash` session inside your container, as a `root` user, under the `/app` directory, this directory has another directory called "app" inside, that's where your code lives inside the container: `/app/app`.
There you can use the `fastapi run --reload` command to run the debug live reloading server.
```console
$ fastapi run --reload app/main.py
```
...it will look like:
```console
root@7f2607af31c3:/app# fastapi run --reload app/main.py
```
and then hit enter. That runs the live reloading server that auto reloads when it detects code changes.
Nevertheless, if it doesn't detect a change but a syntax error, it will just stop with an error. But as the container is still alive and you are in a Bash session, you can quickly restart it after fixing the error, running the same command ("up arrow" and "Enter").
...this previous detail is what makes it useful to have the container alive doing nothing and then, in a Bash session, make it run the live reload server.
## Backend tests
To test the backend run:
To test the backend from the `backend` directory, run:
```console
$ bash ./scripts/test.sh
$ uv run bash ./scripts/test.sh
```
The tests run with Pytest, modify and add tests to `./backend/app/tests/`.
The tests run with Pytest, modify and add tests to `./backend/tests/`.
If you use GitHub Actions the tests will run automatically.
@@ -123,22 +92,14 @@ When the tests are run, a file `htmlcov/index.html` is generated, you can open i
## Migrations
As during local development your app directory is mounted as a volume inside the container, you can also run the migrations with `alembic` commands inside the container and the migration code will be in your app directory (instead of being only inside the container). So you can add it to your git repository.
Make sure you create a "revision" of your models and that you "upgrade" your database with that revision every time you change them. As this is what will update the tables in your database. Otherwise, your application will have errors.
* Start an interactive session in the backend container:
```console
$ docker compose exec backend bash
```
Make sure you create a revision of your models and upgrade the database with that revision every time you change them. From the `backend` directory, use `uv` to run Alembic against the PostgreSQL container:
* Alembic is already configured to import your SQLModel models from `./backend/app/models.py`.
* After changing a model (for example, adding a column), inside the container, create a revision, e.g.:
* After changing a model (for example, adding a column), create a revision:
```console
$ alembic revision --autogenerate -m "Add column last_name to User model"
$ uv run alembic revision --autogenerate -m "Add column last_name to User model"
```
* Commit to the git repository the files generated in the alembic directory.
@@ -146,7 +107,7 @@ $ alembic revision --autogenerate -m "Add column last_name to User model"
* After creating the revision, run the migration in the database (this is what will actually change the database):
```console
$ alembic upgrade head
$ uv run alembic upgrade head
```
If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/core/db.py` that end in:
@@ -165,8 +126,20 @@ If you don't want to start with the default models and want to remove them / mod
## Email Templates
The email templates are in `./backend/app/email-templates/`. Here, there are two directories: `build` and `src`. The `src` directory contains the source files that are used to build the final email templates. The `build` directory contains the final email templates that are used by the application.
The email templates are written with [React Email](https://react.email) in `./packages/react-email/`. The `emails` directory holds one component per email and the `ui` directory holds the shared components (layout, heading, button, link, callout).
Before continuing, ensure you have the [MJML extension](https://marketplace.visualstudio.com/items?itemName=attilabuti.vscode-mjml) installed in your VS Code.
The rendered HTML in `./backend/app/email-templates/` is generated from those components, it is what the application sends, and it shouldn't be edited by hand.
Once you have the MJML extension installed, you can create a new email template in the `src` directory. After creating the new email template and with the `.mjml` file open in your editor, open the command palette with `Ctrl+Shift+P` and search for `MJML: Export to HTML`. This will convert the `.mjml` file to a `.html` file and now you can save it in the build directory.
To preview the emails while editing them, start the dev server from the root of the project:
```console
$ bun run email:dev
```
Values coming from the backend are declared as Jinja placeholders in the component props, for example `username = "{{ username }}"`. The context for each email is built in `generate_*_email()` in `./backend/app/utils.py`, so a new placeholder needs to be added there too.
Once you are done, regenerate the templates used by the application:
}</style><styletype="text/css"></style></head><bodystyle="background-color:#fafbfc;"><divstyle="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><divstyle="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><tablealign="center"border="0"cellpadding="0"cellspacing="0"role="presentation"style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><tdstyle="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><divclass="mj-column-per-100 outlook-group-fix"style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><tableborder="0"cellpadding="0"cellspacing="0"role="presentation"style="vertical-align:middle;"width="100%"><tr><tdalign="center"style="font-size:0px;padding:35px;word-break:break-word;"><divstyle="font-family:Arial, Helvetica, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }} - Password Recovery</div></td></tr><tr><tdalign="center"style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><divstyle="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Hello {{ username }}</span></div></td></tr><tr><tdalign="center"style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><divstyle="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">We've received a request to reset your password. You can do it by clicking the button below:</div></td></tr><tr><tdalign="center"vertical-align="middle"style="font-size:0px;padding:15px 30px;word-break:break-word;"><tableborder="0"cellpadding="0"cellspacing="0"role="presentation"style="border-collapse:separate;line-height:100%;"><tr><tdalign="center"bgcolor="#009688"role="presentation"style="border:none;border-radius:8px;cursor:auto;padding:10px 25px;background:#009688;"valign="middle"><ahref="{{ link }}"style="background:#009688;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:18px;font-weight:normal;line-height:120%;Margin:0;text-decoration:none;text-transform:none;"target="_blank">Reset password</a></td></tr></table></td></tr><tr><tdalign="center"style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><divstyle="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Or copy and paste the following link into your browser:</div></td></tr><tr><tdalign="center"style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><divstyle="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><ahref="{{ link }}">{{ link }}</a></div></td></tr><tr><tdalign="center"style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><divstyle="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">This password will expire in {{ valid_hours }} hours.</div></td></tr><tr><tdstyle="font-size:0px;padding:10px 25px;word-break:break-word;"><pstyle="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;">
</td></tr></table><![endif]--></td></tr><tr><tdalign="center"style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><divstyle="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:1;text-align:center;color:#555555;">If you didn't request a password recovery you can disregard this email.</div></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
<mj-text align="center" padding="35px" font-size="20px" color="#333">{{ project_name }} - New Account</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><span>Welcome to your new account!</span></mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Here are your account details:</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">We've received a request to reset your password. You can do it by clicking the button below:</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Or copy and paste the following link into your browser:</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><a href="{{ link }}">{{ link }}</a></mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">This password will expire in {{ valid_hours }} hours.</mj-text>
<mj-text align="center" font-size="14px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">If you didn't request a password recovery you can disregard this email.</mj-text>
You can deploy the project using Docker Compose to a remote server.
This project expects you to have a Traefik proxy handling communication to the outside world and HTTPS certificates.
The deployment Docker Compose configuration includes Traefik to handle HTTPS and route incoming traffic to the application.
You can use CI/CD (continuous integration and continuous deployment) systems to deploy automatically, there are already configurations to do it with GitHub Actions.
@@ -10,147 +10,28 @@ But you have to configure a couple things first. 🤓
## Preparation
* Have a remote server ready and available.
* Configure the DNS records of your domain to point to the IP of the server you just created.
* Configure a wildcard subdomain for your domain, so that you can have multiple subdomains for different services, e.g. `*.fastapi-project.example.com`. This will be useful for accessing different components, like `dashboard.fastapi-project.example.com`, `api.fastapi-project.example.com`, `traefik.fastapi-project.example.com`, `adminer.fastapi-project.example.com`, etc. And also for `staging`, like `dashboard.staging.fastapi-project.example.com`, `adminer.staging..fastapi-project.example.com`, etc.
* Have a remote server ready and available. Use a separate server for each environment, for example one for staging and one for production.
* Configure DNS records pointing to the server for the application domain and any supporting service subdomains you want to expose, e.g. `fastapi-project.example.com` and `adminer.fastapi-project.example.com`.
* Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop).
## Public Traefik
We need a Traefik proxy to handle incoming connections and HTTPS certificates.
You need to do these next steps only once.
### Traefik Docker Compose
* Create a remote directory to store your Traefik Docker Compose file:
```bash
mkdir -p /root/code/traefik-public/
```
Copy the Traefik Docker Compose file to your server. You could do it by running the command `rsync` in your local terminal:
```bash
rsync -a docker-compose.traefik.yml root@your-server.example.com:/root/code/traefik-public/
```
### Traefik Public Network
This Traefik will expect a Docker "public network" named `traefik-public` to communicate with your stack(s).
This way, there will be a single public Traefik proxy that handles the communication (HTTP and HTTPS) with the outside world, and then behind that, you could have one or more stacks with different domains, even if they are on the same single server.
To create a Docker "public network" named `traefik-public` run the following command in your remote server:
```bash
docker network create traefik-public
```
### Traefik Environment Variables
The Traefik Docker Compose file expects some environment variables to be set in your terminal before starting it. You can do it by running the following commands in your remote server.
* Create the username for HTTP Basic Auth, e.g.:
```bash
export USERNAME=admin
```
* Create an environment variable with the password for HTTP Basic Auth, e.g.:
```bash
export PASSWORD=changethis
```
* Use openssl to generate the "hashed" version of the password for HTTP Basic Auth and store it in an environment variable:
To verify that the hashed password is correct, you can print it:
```bash
echo $HASHED_PASSWORD
```
* Create an environment variable with the domain name for your server, e.g.:
```bash
export DOMAIN=fastapi-project.example.com
```
* Create an environment variable with the email for Let's Encrypt, e.g.:
```bash
export EMAIL=admin@example.com
```
**Note**: you need to set a different email, an email `@example.com` won't work.
### Start the Traefik Docker Compose
Go to the directory where you copied the Traefik Docker Compose file in your remote server:
```bash
cd /root/code/traefik-public/
```
Now with the environment variables set and the `docker-compose.traefik.yml` in place, you can start the Traefik Docker Compose running the following command:
```bash
docker compose -f docker-compose.traefik.yml up -d
```
## Deploy the FastAPI Project
Now that you have Traefik in place you can deploy your FastAPI project with Docker Compose.
You can deploy your FastAPI project with Docker Compose.
**Note**: You might want to jump ahead to the section about Continuous Deployment with GitHub Actions.
Note: `--filter=":- .gitignore"` tells `rsync` to use the same rules as git, ignore files ignored by git, like the Python virtual environment.
## Environment Variables
You need to set some environment variables first.
Set the `ENVIRONMENT`, by default `local` (for development), but when deploying to a server you would put something like `staging` or `production`:
```bash
export ENVIRONMENT=production
```
Set the `DOMAIN`, by default `localhost` (for development), but when deploying you would use your own domain, for example:
```bash
export DOMAIN=fastapi-project.example.com
```
You can set several variables, like:
* `PROJECT_NAME`: The name of the project, used in the API for the docs and emails.
* `STACK_NAME`: The name of the stack used for Docker Compose labels and project name, this should be different for `staging`, `production`, etc. You could use the same domain replacing dots with dashes, e.g. `fastapi-project-example-com` and `staging-fastapi-project-example-com`.
* `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas.
* `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens.
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
* `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser.
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
* `SMTP_USER`: The SMTP server user to send emails.
* `SMTP_PASSWORD`: The SMTP server password to send emails.
* `EMAILS_FROM_EMAIL`: The email account to send emails from.
* `POSTGRES_SERVER`: The hostname of the PostgreSQL server. You can leave the default of `db`, provided by the same Docker Compose. You normally wouldn't need to change this unless you are using a third-party provider.
* `POSTGRES_PORT`: The port of the PostgreSQL server. You can leave the default. You normally wouldn't need to change this unless you are using a third-party provider.
* `POSTGRES_PASSWORD`: The Postgres password.
* `POSTGRES_USER`: The Postgres user, you can leave the default.
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`.
* `SENTRY_DSN`: The DSN for Sentry, if you are using it.
## GitHub Actions Environment Variables
There are some environment variables only used by GitHub Actions that you can configure:
* `LATEST_CHANGES`: Used by the GitHub Action [latest-changes](https://github.com/tiangolo/latest-changes) to automatically add release notes based on the PRs merged. It's a personal access token, read the docs for details.
* `SMOKESHOW_AUTH_KEY`: Used to handle and publish the code coverage using [Smokeshow](https://github.com/samuelcolvin/smokeshow), follow their instructions to create a (free) Smokeshow key.
### Generate secret keys
Some environment variables in the `.env` file have a default value of `changethis`.
* `PROJECT_NAME`: The name of the project, used in the API for the docs and emails.
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
* `SMTP_USER`: The SMTP server user to send emails.
* `SMTP_PASSWORD`: The SMTP server password to send emails.
* `EMAILS_FROM_EMAIL`: The email account to send emails from.
* `POSTGRES_USER`: The Postgres user, you can leave the default.
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`.
* `SENTRY_DSN`: The DSN for Sentry, if you are using it.
## GitHub Actions Environment Variables
There are some environment variables only used by GitHub Actions that you can configure:
* `LATEST_CHANGES`: Used by the GitHub Action [latest-changes](https://github.com/tiangolo/latest-changes) to automatically add release notes based on the PRs merged. It's a personal access token, read the docs for details.
* `SMOKESHOW_AUTH_KEY`: Used to handle and publish the code coverage using [Smokeshow](https://github.com/samuelcolvin/smokeshow), follow their instructions to create a (free) Smokeshow key.
### Deploy with Docker Compose
With the environment variables in place, you can deploy with Docker Compose:
docker compose -f compose.yml -f compose.deploy.yml up -d
```
For production you wouldn't want to have the overrides in `docker-compose.override.yml`, that's why we explicitly specify `docker-compose.yml` as the file to use.
The `compose.deploy.yml` file adds the deployment settings to the shared configuration in `compose.yml`, including HTTPS and automatic certificate handling. Explicitly listing these files also excludes the local development settings in `compose.override.yml`.
## Continuous Deployment (CD)
You can use GitHub Actions to deploy your project automatically. 😎
You can have multiple environment deployments.
There are already two environments configured, `staging` and `production`. 🚀
There are already two environment deployments configured, `staging` and `production`. Each environment should be deployed to a separate server. 🚀
### Install GitHub Actions Runner
@@ -253,23 +182,32 @@ cd /home/github/actions-runner
You can read more about it in the official guide: [Configuring the self-hosted runner application as a service](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/configuring-the-self-hosted-runner-application-as-a-service).
### Configure GitHub Environments
The deployment workflows use [GitHub Environments](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments) for `staging` and `production`. This enables environment-specific secrets, deployment protection rules (e.g. required reviewers, wait timers), and deployment status tracking.
To configure them, go to your repository's **Settings** > **Environments** and create the `staging` and `production` environments.
### Set Secrets
On your repository, configure secrets for the environment variables you need, the same ones described above, including `SECRET_KEY`, etc. Follow the [official GitHub guide for setting repository secrets](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository).
For each GitHub Environment (`staging` and `production`), configure the required secrets as [environment secrets](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets#creating-secrets-for-an-environment). Environment secrets are preferred over [repository secrets](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets#creating-secrets-for-a-repository) because they are scoped to the specific environment, reducing exposure and aligning with any protection rules you configure.
The current Github Actions workflows expect these secrets:
The deployment workflows require these secrets:
* `DOMAIN_PRODUCTION`
* `DOMAIN_STAGING`
* `STACK_NAME_PRODUCTION`
* `STACK_NAME_STAGING`
* `EMAILS_FROM_EMAIL`
* `DOMAIN`
* `FIRST_SUPERUSER`
* `FIRST_SUPERUSER_PASSWORD`
* `POSTGRES_PASSWORD`
* `SECRET_KEY`
* `LATEST_CHANGES`
* `SMOKESHOW_AUTH_KEY`
To enable emails, configure these additional secrets with the values from your email provider:
* `SMTP_HOST`
* `SMTP_USER`
* `SMTP_PASSWORD`
* `EMAILS_FROM_EMAIL`
To enable Sentry, configure the `SENTRY_DSN` secret.
## GitHub Action Deployment Workflows
@@ -278,32 +216,34 @@ There are GitHub Action workflows in the `.github/workflows` directory already c
* `staging`: after pushing (or merging) to the branch `master`.
* `production`: after publishing a release.
Both workflows are associated with their respective GitHub Environments, so deployments will be visible in the repository's **Environments** section and will respect any protection rules you configure.
### Prepare a Release
Install the [PR Submit GitHub App](https://github.com/apps/pr-submit) in your repository to enable the **Prepare Release** workflow.
Run the workflow manually from the **Actions** tab and select the version bump. It creates a pull request that updates the release notes. When you merge that pull request, the **Create Draft Release** workflow creates a draft GitHub release with the corresponding release notes.
Review and publish the draft release to trigger the production deployment.
If you need to add extra environments you could use those as a starting point.
## URLs
Replace `fastapi-project.example.com` with your domain.
* Now you can open your browser and interact with these URLs:
Frontend, built with Docker, with routes handled based on the path: http://localhost:5173
Backend, JSON based web API based on OpenAPI: http://localhost:8000
Automatic interactive documentation with Swagger UI (from the OpenAPI backend): http://localhost:8000/docs
Adminer, database web administration: http://localhost:8080
Traefik UI, to see how the routes are being handled by the proxy: http://localhost:8090
**Note**: The first time you start your stack, it might take a minute for it to be ready. While the backend waits for the database to be ready and configures everything. You can check the logs to monitor it.
To check the logs, run (in another terminal):
```bash
docker compose logs
```
To check the logs of a specific service, add the name of the service, e.g.:
```bash
docker compose logs backend
```
## Local Development
The Docker Compose files are configured so that each of the services is available in a different port in `localhost`.
For local development, run PostgreSQL and Mailcatcher with Docker Compose, and run the FastAPI and Vite development servers locally.
For the backend and frontend, they use the same port that would be used by their local development server, so, the backend is at `http://localhost:8000` and the frontend at `http://localhost:5173`.
This way, you could turn off a Docker Compose service and start its local development service, and everything would keep working, because it all uses the same ports.
For example, you can stop that `frontend` service in the Docker Compose, in another terminal, run:
Start the supporting services:
```bash
docker compose stop frontend
docker compose up -d db mailcatcher
```
And then start the local frontend development server:
Then, from the `backend` directory, install the dependencies and prepare the database:
```bash
cd frontend
npm run dev
uv sync
uv run bash scripts/prestart.sh
```
Or you could stop the `backend` Docker Compose service:
Start the FastAPI development server:
```bash
docker compose stop backend
uv run fastapi dev
```
And then you can run the local development server for the backend:
In another terminal, from the project root, install the frontend dependencies and start the Vite development server:
```bash
cd backend
fastapi dev app/main.py
bun install
bun run dev
```
## Docker Compose in `localhost.tiangolo.com`
Now you can open these URLs:
When you start the Docker Compose stack, it uses `localhost` by default, with different ports for each service (backend, frontend, adminer, etc).
Frontend development server: <http://localhost:5173>
When you deploy it to production (or staging), it will deploy each service in a different subdomain, like `api.example.com` for the backend and `dashboard.example.com` for the frontend.
Backend API: <http://localhost:8000>
In the guide about [deployment](deployment.md) you can read about Traefik, the configured proxy. That's the component in charge of transmitting traffic to each service based on the subdomain.
Automatic interactive API documentation with Swagger UI: <http://localhost:8000/docs>
If you want to test that it's all working locally, you can edit the local `.env` file, and change:
Mailcatcher: <http://localhost:1080>
```dotenv
DOMAIN=localhost.tiangolo.com
```
The frontend development server uses the backend at `http://localhost:8000`, as configured in `frontend/.env`.
That will be used by the Docker Compose files to configure the base domain for the services.
### Frontend Served by FastAPI
Traefik will use this to transmit traffic at `api.localhost.tiangolo.com` to the backend, and traffic at `dashboard.localhost.tiangolo.com` to the frontend.
The domain `localhost.tiangolo.com` is a special domain that is configured (with all its subdomains) to point to `127.0.0.1`. This way you can use that for your local development.
After you update it, run again:
Build the frontend from the `frontend` directory:
```bash
bun run build
```
The build is written to `backend/app/frontend` and served by FastAPI at <http://localhost:8000>. Rebuild the frontend after making frontend changes.
## Full Stack with Docker Compose
To run the backend and built frontend in Docker Compose:
```bash
docker compose run --rm backend bash scripts/prestart.sh
docker compose watch
```
When deploying, for example in production, the main Traefik is configured outside of the Docker Compose files. For local development, there's an included Traefik in `docker-compose.override.yml`, just to let you test that the domains work as expected, for example with `api.localhost.tiangolo.com` and `dashboard.localhost.tiangolo.com`.
Now you can open these URLs:
Application, with the frontend and API served by FastAPI: <http://localhost:8000>
Automatic interactive API documentation with Swagger UI: <http://localhost:8000/docs>
Adminer, database web administration: <http://localhost:8080>
Traefik UI, to see how the routes are being handled by the proxy: <http://localhost:8090>
Mailcatcher: <http://localhost:1080>
Stop a locally running FastAPI server before starting the Compose backend because both use port `8000`.
**Note**: The first time you start the stack, it might take a minute for all the services to be ready. To monitor it, use `docker compose logs`, or `docker compose logs backend` for the backend service.
## Mailcatcher
Mailcatcher captures emails sent during local development instead of delivering them. The local backend connects to it at `localhost:1025`, and the Compose backend connects to the `mailcatcher` service. Captured emails are available at <http://localhost:1080>.
## Docker Compose files and env vars
There is a main `docker-compose.yml` file with all the configurations that apply to the whole stack, it is used automatically by `docker compose`.
There is a main `compose.yml` file with all the configurations that apply to the whole stack, it is used automatically by `docker compose`.
And there's also a `docker-compose.override.yml` with overrides for development, for example to mount the source code as a volume. It is used automatically by `docker compose` to apply overrides on top of `docker-compose.yml`.
And there's also a `compose.override.yml` with overrides for development, for example to mount the source code as a volume. It is used automatically by `docker compose` to apply overrides on top of `compose.yml`.
These Docker Compose files use the `.env` file containing configurations to be injected as environment variables in the containers.
The`compose.deploy.yml` file contains the deployment-specific settings, including HTTPS and automatic certificate handling. It is explicitly combined with `compose.yml` when deploying the application.
They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command.
The backend reads local settings from the `.env` file. Docker Compose also uses it for variable interpolation and passes the settings each container needs.
After changing variables, make sure you restart the stack:
@@ -114,56 +99,59 @@ docker compose watch
## The .env file
The `.env` file is the one that contains all your configurations, generated keys and passwords, etc.
The `.env` file contains the shared local defaults, generated keys, passwords, and other configuration. Its hostnames use `localhost` for processes running on your machine. Docker Compose overrides hostnames such as the database and SMTP server with their Compose service names.
Depending on your workflow, you could want to exclude it from Git, for example if your project is public. In that case, you would have to make sure to set up a way for your CI tools to obtain it while building or deploying your project.
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file.
One way to do it could be to add each environment variable to your CI/CD system.
## Pre-commits and code linting
we are using a tool called [pre-commit](https://pre-commit.com/) for code linting and formatting.
we are using a tool called [prek](https://prek.j178.dev/) (modern alternative to [Pre-commit](https://pre-commit.com/)) for code linting and formatting.
When you install it, it runs right before making a commit in git. This way it ensures that the code is consistent and formatted even before it is committed.
You can find a file `.pre-commit-config.yaml` with configurations at the root of the project.
#### Install pre-commit to run automatically
#### Install prek to run automatically
`pre-commit` is already part of the dependencies of the project, but you could also install it globally if you prefer to, following [the official pre-commit docs](https://pre-commit.com/).
`prek` is already part of the dependencies of the project.
After having the `pre-commit` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit.
After having the `prek` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit.
Using `uv`, you could do it with:
Using `uv`, you could do it with (make sure you are inside `backend` folder):
```bash
❯ uv run pre-commit install
pre-commit installed at .git/hooks/pre-commit
❯ uv run prek install -f
prek installed at `../.git/hooks/pre-commit`
```
The `-f` flag forces the installation, in case there was already a `pre-commit` hook previously installed.
Now whenever you try to commit, e.g. with:
```bash
git commit
```
...pre-commit will run and check and format the code you are about to commit, and will ask you to add that code (stage it) with git again before committing.
...prek will run and check and format the code you are about to commit, and will ask you to add that code (stage it) with git again before committing.
Then you can `git add` the modified/fixed files again and now you can commit.
#### Running pre-commit hooks manually
#### Running prek hooks manually
you can also run `pre-commit` manually on all the files, you can do it using `uv` with:
you can also run `prek` manually on all the files, you can do it using `uv` with:
```bash
❯ uv run pre-commit run --all-files
❯ uv run prek run --all-files
check for added large files..............................................Passed
# Enable the Traefik log, for configurations and errors
- --log
# Enable the Dashboard and API
- --api
networks:
# Use the public network created to be shared between Traefik and
# any other service that needs to be publicly available with HTTPS
- traefik-public
volumes:
# Create a volume to store the certificates, even if the container is recreated
traefik-public-certificates:
networks:
# Use the previously created public network "traefik-public", shared with other
# services that need to be publicly available via this Traefik
traefik-public:
external:true
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.