Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Configurable template for a FastAPI application, with Authentication, User integration, Admin pages and a snappy CLI to control it all!

License

NotificationsYou must be signed in to change notification settings

seapagan/fastapi-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

GitHub ReleaseRuffTestsCode CoverageCode Qualitypages-build-deployment

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

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.

Breaking Changes

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.

Changes from version 0.4.x

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.git

Be aware that this branch will not be maintained and will not receive anyupdates or bug fixes.

Functionality

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 Keys are 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-Key header.
  • ARefresh Token with 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 thesqladmin package to give you an easy way to manage your database.
  • Uses the python logger for info/warning/error logging - tying transparently into theuvicorn logger.
  • 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.env file 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! 😃

Installation

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.

Docker

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.

Develop on containers

⚠️ For local use rename.env.example to.env.

It is possible to develop directly on Docker containers :

Usingdocker compose up (recommended):

docker compose up

To run and rebuild image (dependency updates):

docker compose up --build

To remove all containers:

docker compose down

Usingdocker compose run:

First run migrations:

docker compose run --rm api alembic upgrade head

Run containers:

docker compose run --rm --service-ports api uvicorn --host 0.0.0.0 main:app --reload

To rebuild image (dependency updates):

docker compose build

Migrations on containers

Running migrations on Docker container is also possible:

docker compose run --rm api alembic upgrade head

Testing on containers

Running tests on Docker container is also possible:

docker compose run --rm api pytest

Planned Functionality and Known Bugs

See theTODO.md file for plans and known issues.

Testing

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:

$pytest

It 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.

Code Quality

To be written

Who is Using this Template?

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 😃.

Contributing

SeeContributing for details on how to contribute to this project.

GitHub Discussions

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

Stars

Watchers

Forks

Contributors5

Languages


[8]ページ先頭

©2009-2025 Movatter.jp