Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork15
A Configurable template for a FastAPI application, with Authentication, User integration, Admin pages and a snappy CLI to control it all!
License
seapagan/fastapi-template
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This is a template Repository for starting a newFastAPI project with Authentication and Users,with Authorization already baked-in.
Documentation for this project is now availiable on it's own page athttps://api-template.seapagan.net. This is a work in progress, and whenfinished will include full usage information and how-to's.
- Important note on Versioning
- Breaking Changes
- Changes from version 0.4.x
- Functionality
- Installation
- Docker
- Planned Functionality and Known Bugs
- Testing
- Code Quality
- Who is Using this Template?
- Contributing
- GitHub Discussions
This template versioning has been refactored to start fromVersion 0.4.0.
The original template was written for my own use and probably promoted to V1.0.0before it should have been, and there have been many updates and fixes sincethen.
I will keep the old releases available for those who wish to use them (for ashort time). It's better to do this now before more users need to update theirprojects to future versions.
All releases from now on will also contain a Git patch to upgrade from theprevious version. This will be in the form of a.patch file which can beapplied to their project using thegit apply command. This will be documentedin the release notes.
There will be breaking changes implemented from time to time, as the template isstill evolving. These may be due to security issues or changes in philosophy.These can always be foundhereon the website.
Starting from version 0.5.0, the template has been refactored to use SQLAlchemy2.0 ORM instead ofencode/databases for database access. This allows for amore flexible and powerful Asynchronous database access but does need a bit ofrefactoring for any existing projects. See thedocumentation formore information. I will also be adding a migration guide for those who wish toupgrade their existing projects (time permitting).
If you prefer to continue using the 0.4.x branch, you can find ithere.
To use this branch you will need to clone the repository and checkout the0.4.2 branch.
git clone -b 0.4.2 https://github.com/seapagan/fastapi-template.gitBe aware that this branch will not be maintained and will not receive anyupdates or bug fixes.
This template is a ready-to-use boilerplate for a FastAPI project. It has thefollowing advantages to starting your own from scratch :
- Baked-in User database and management. Routes are provided toadd/edit/delete/search or ban (and unban) Users.
- Postgresql Integration, using SQLAlchemy ORM, no need for raw SQL queries(unless you want to!). All database usage is Asynchronous.Alembicis used to control database migrations.
- Register and Login routes provided, both of which return a JWT token to beused in all future requests. JWT Token expires 120 minutes after issue.
- JWT-based security as a Bearer Token to control access to all your routes.
API Keysare fully implemented and can be used by registered users insteadof the JTW. These willnot expire at present though adding expiry is afuture plan. API keys are passed using theX-API-Keyheader.- A
Refresh Tokenwith 30 day expiry is sent at time of register or login(never again). This will enable easy re-authentication when the JWT expireswithout needing to send username or password again, and should be doneautomatically by the Front-End. - A clean layout to help structure your project.
- An optionalAdmin site to manage users and API keys. This uses the
sqladminpackage to give you an easy way to manage your database. - Uses the python logger for info/warning/error logging - tying transparently into the
uvicornlogger. - A command-line admin tool. This allows to configure the project metadatavery easily, add users (and make admin), and run a development server. Thiscan easily be modified to add your own functionality (for example bulk adddata) since it is based on the excellentTyper library.
- Easily batch-add random test users to the database for testing/developmentpurposes using the CLI or seed the database with pre-set users from a CSVfile.
- Database and Secrets are automatically read from Environment variables or a
.envfile if that is provided. The CLI can generate and set the JTW Secretand Admin pages encryption keys. - User email is validated for correct format on creation (however no checks areperformed to ensure the email or domain actually exists).
- Control permitted CORS Origin through Environment variables.
- Manager class set up to send emails to users, and by default an email is sentwhen new users register. The content is set by a template (currently a basicplaceholder). This email has a link for the user to confirm their emailaddress - until this is done, the user cannot user the API.
- Docker and Compose file set up to develop and test this API using Docker
This template is still in very active development and probably not yet readyfor full production use. However, I am currently using it to develop my ownprojects, which include some production API's without issues. I will update thetemplate as I find bugs or add new features. I will also be adding moredocumentation as I go. For the moment, if you wish to use it without gettinginvolved in dev, I'd recommend checking out the latest actualRelease.
However, themain branch should be pretty stable as all development is done onthedevelop branch and merged intomain when ready.
The templateRequires Python 3.9.0 or higher. I actually develop underPython 3.13.x where x is the latest patch version available at the time, andmigrating to the next patch version as soon as it is released. CI tests are runautomatically on the latest patch levels of Python 3.9 to 3.13.
This template is free to use but I would request some accreditation. If you douse it in one of your applications, or even some of the unique code from thetemplate, or you learn something from it, please put a small note in your readmeor blog post/whatever stating that you used this Template or code therein, witha link back to this repository. Thank You 😊
For those who let me know they are using this Template, I'll add links back toyour project in this documentation.
If this template saves you time/effort/money, or you just wish to show yourappreciation for my work, why notSponsor my Work orBuy me aCoffee! 😃
Click the 'Use this template' button at the top of the Repository on GitHub.This will create a new repository in your personal GitHub account (Not a Fork)which you can then Clone and start working on.
It is assumed that you have at least some knowledge ofFastAPI to usethis template, there are very goodBasic andAdvanced User Guides on the FastAPI website .
Visit theInstallation Instructions for more detailed installationnotes, including how to handle the coverage uploader.
Note that when run from docker, the API is exposed on port8001 instead of8000.
Also, unlike before version 0.5.1, it is no longer required to change theDB_ADDRESS environment variable when running on docker, this is taken care ofautomatically.
⚠️ For local use rename.env.exampleto.env.
It is possible to develop directly on Docker containers :
Usingdocker compose up (recommended):
docker compose upTo run and rebuild image (dependency updates):
docker compose up --buildTo remove all containers:
docker compose downUsingdocker compose run:
First run migrations:
docker compose run --rm api alembic upgrade headRun containers:
docker compose run --rm --service-ports api uvicorn --host 0.0.0.0 main:app --reloadTo rebuild image (dependency updates):
docker compose buildRunning migrations on Docker container is also possible:
docker compose run --rm api alembic upgrade headRunning tests on Docker container is also possible:
docker compose run --rm api pytestSee theTODO.md file for plans and known issues.
This project has a test suite for Integration and Unit tests. We usepytest for this.
Currently you need a Postgresql database running for this to work, howeverSQLite support is planned to be re-added. You can easily set up a Postgresqldatabase using Docker.
Before running the tests, you need to create a dedicated test database, in isassumed that the server, username and password are the same as for the maindatabase.
Edit the setting in.env to point to the test database:
# Database name to use for testing. This must already exist.TEST_DB_NAME=api-template-test
You can then migrate this empty database by running:
$api-admintest setupMigrating the test database ... Done!
Tests can then be run from the checked out code with:
$pytestIt is possible to run either the Unit or Integration tests separately usingpytest -m unit orpytest -m integration
Full tests will be run automatically byGitHub Actions on every new commitpushed up to the remote repository. Code Coverage is also checked and notedafter each test suite is run.
To be written
Meh, at the moment probably no-one except me 😆. If you do use this in one ofyour own projects, drop me a message and I'll add your profile and project linkshere 😃.
SeeContributing for details on how to contribute to this project.
I have enabledDiscussions on this repository, so if you have anyquestions, suggestions or just want to chat about this template, please feelfree to start a discussion.
About
A Configurable template for a FastAPI application, with Authentication, User integration, Admin pages and a snappy CLI to control it all!
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Contributors5
Uh oh!
There was an error while loading.Please reload this page.