This is an example of how to use FastAPI with
JWT authentication, using the
fastapi_users library. It also
has async database access using SQLAlchemy
Currently uses SQLite as the database, but can be easily changed to any other database. It largely follows the example in the fastapi-users documentation, however I have laid the project out in a way that I find more readable and maintainable.
We use the database
strategy
instead of the default jwt strategy, as it allows us to invalidate tokens on
the server side. For the Transport, we use the
Bearer
strategy where the token is sent in the Authorization header.
The project uses uv to manage the dependencies. To install the dependencies and switch to the virtual environment, run:
uv sync
source .venv/bin/activate # On Windows, use .venv\Scripts\activateNow you can run the project with:
python main.pyNote
The above uses the --reload option, so the server will restart whenever you
change a file. This is useful for development, but not recommended for
production.
The project will be available at http://localhost:8000.
You can access the API documentation at http://localhost:8000/docs (or
http://localhost:8000/redoc if you prefer that).