Giter VIP home page Giter VIP logo

seapagan / fastapi-template Goto Github PK

View Code? Open in Web Editor NEW
87.0 3.0 6.0 13.45 MB

Configurable template for a FastAPI application, with Authentication and User integration.

Home Page: https://api-template.seapagan.net

License: MIT License

Python 98.30% Mako 0.24% CSS 0.23% HTML 0.85% Dockerfile 0.29% Shell 0.09%
fastapi python template jwt jwt-authentication async async-test sqlalchemy sqlalchemy2 alembic

fastapi-template's Introduction

FastAPI Application Template

GitHub Release Ruff Tests codecov pages-build-deployment Codacy Badge

This is a template Repository for starting a new FastAPI project with Authentication and Users, with Authorization already baked-in.

Documentation for this project is now availiable on it's own page at https://api-template.seapagan.net. This is a work in progress, and when finished will include full usage information and how-to's.

Important note on Versioning

This template versioning has been refactored to start from Version 0.4.0.

The original template was written for my own use and probably promoted to V1.0.0 before it should have been, and there have been many updates and fixes since then.

I will keep the old releases available for those who wish to use them (for a short time). It's better to do this now before more users need to update their projects to future versions.

All releases from now on will also contain a Git patch to upgrade from the previous version. This will be in the form of a .patch file which can be applied to their project using the git apply command. This will be documented in the release notes.

Changes from version 0.4.x

Starting from version 0.5.0, the template has been refactored to use SQLAlchemy 2.0 ORM instead of encode/databases for database access. This allows for a more flexible and powerful Asynchronous database access but does need a bit of refactoring for any existing projects. See the documentation for more information. I will also be adding a migration guide for those who wish to upgrade their existing projects (time permitting).

If you prefer to continue using the 0.4.x branch, you can find it here.

To use this branch you will need to clone the repository and checkout the 0.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 any updates or bug fixes.

Functionality

This template is a ready-to-use boilerplate for a FastAPI project. It has the following advantages to starting your own from scratch :

  • Baked-in User database and management. Routes are provided to add/edit/delete 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. Alembic is used to control database migrations.
  • Register and Login routes provided, both of which return a JWT token to be used 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.
  • A Refresh Token with 30 day expiry is sent at time of register or login (never again). This will enable easy re-authentication when the JWT expires without needing to send username or password again, and should be done automatically by the Front-End.
  • A clean layout to help structure your project.
  • A command-line admin tool. This allows to configure the project metadata very easily, add users (and make admin), and run a development server. This can easily be modified to add your own functionality (for example bulk add data) since it is based on the excellent asyncclick library.
  • Database and Secrets are automatically read from Environment variables or a .env file if that is provided.
  • User email is validated for correct format on creation (however no checks are performed 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 sent when new users register. The content is set by a template (currently a basic placeholder). This email has a link for the user to confirm their email address - 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 is not yet ready for full production use. However, I am currently using it to develop my own projects, which include some production API's without issues. I will update the template as I find bugs or add new features. I will also be adding more documentation as I go. For the moment, if you wish to use it without getting involved in dev, I'd recommend checking out the latest actual Release.

However, the main branch should be pretty stable as all development is done on the develop branch and merged into main when ready.

The template Requires Python 3.9.0+ or higher. It is developed under Python 3.11.x where x is the latest version available at the time, and migrating to the next patch version as soon as it is released.

This template is free to use but I would request some accreditation. If you do use it in one of your applications, please put a small note in your readme stating that you based your project on this Template, with a link back to this repository. Thank You ๐Ÿ˜Š

For those who let me know they are using this Template, I'll add links back to your project in this documentation.

If this template saves you time/effort/money, or you just wish to show your appreciation for my work, why not Buy me a Coffee! ๐Ÿ˜ƒ

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 of FastAPI to use this template, there are very good Basic and Advanced User Guides on the FastAPI website .

Visit the Installation Instructions for more detailed installation notes, including how to handle the coverage uploader.

Docker

Note that when run from docker, the API is exposed on port 8001 instead of 8000.

Also, unlike before version 0.5.1, it is no longer required to change the DB_ADDRESS environment variable when running on docker, this is taken care of automatically.

Develop on containers

โš ๏ธ For local use rename .env.example to .env.

It is possible to develop directly on Docker containers :

Using docker compose up (recommended):

docker compose up

To run and rebuild image (dependency updates):

docker compose up --build

To remove all containers:

docker compose down

Using docker 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

See the TODO.md file for plans.

Testing

This project has a test suite for Integration and Unit tests. We use pytest for this.

Currently you need a Postgresql database running for this to work, however SQLite support is planned to be re-added. You can easily set up a Postgresql database using Docker.

Before running the tests, you need to create a dedicated test database, in is assumed that the server, username and password are the same as for the main database.

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-admin test setup
Migrating 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 using pytest -m unit or pytest -m integration

Full tests will be run automatically by GitHub Actions on every new commit pushed up to the remote repository. Code Coverage is also checked and noted after each test suite is run.

Code Quality

To be written

Known Bugs

See the BUGS.md file for known bugs.

Who is Using this Template?

Meh, at the moment probably no-one except me ๐Ÿ˜†. If you do use this in one of your own projects, drop me a message and I'll add your profile and project links here ๐Ÿ˜ƒ.

Contributing

See Contributing for details on how to contribute to this project.

GitHub Discussions

I have enabled Discussions on this repository, so if you have any questions, suggestions or just want to chat about this template, please feel free to start a discussion.

fastapi-template's People

Contributors

dependabot[bot] avatar pdrivom avatar pre-commit-ci[bot] avatar seapagan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

fastapi-template's Issues

Feature Request: Social Auth

Is your feature request related to a problem? Please describe.
I'd like to be able to use social accounts for authentication(GitHub, twitter, Google etc). Is it possible to integrate that into this project?

Add unit tests

Please add unit tests so we can check if the project works.

Improvements to the CLI metadata setup

Improvement suggestions for the ./api-admin custom metadata command:

  1. Enter the current year into the template.
  2. Allow changing the API version, option to set to 0.0.1

Run Tests against Postgres database

Is your feature request related to a problem? Please describe.
It would be better to use the same type of database to run tests. If any breaking changes on database connection layer (either code or package update) would not be hidden on tests.

Describe the solution you'd like
Switch from SQLite to Postgres.

Extra info
I can work on it.

Key Management secrets engine

Is your feature request related to a problem? Please describe.
Storing JWT encryption key on a server, it's not the most secure option. Using a Key Management engine, makes it safer for production setting.

Describe the solution you'd like
Use Hashicorp Vault integration for DB credentials (with auto-rotating), JWT secrets, etc.

Intermittent test failures with 3.9 and 3.10

Describe the bug

Tests (on develop branch) fail intermittently under Python 3.9 and 3.10, only on GitHub CI not locally

To Reproduce

Run the CI manually or automatically after a PR/Commit push

Expected behavior

Tests all pass

Screenshots

fastapi-template-test-fails

Additional context

Looks to be an issue with the pyfakefs package, or more likely the way I am using it.

Poetry install broken under Docker

Describe the bug
Cloning the repo, and running docker compose up --build fails.

To Reproduce
Steps to reproduce the behavior:

  1. Clone the main branch locally
  2. Run docker compose up --build
19.53   โ€ข Installing pygithub (2.1.1)
19.79 
19.79   ChefBuildError
19.79 
19.79   Backend subprocess exited when trying to invoke get_requires_for_build_wheel
19.79   
19.79   Traceback (most recent call last):
19.79     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
19.79       main()
19.79     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 335, in main
19.79       json_out['return_val'] = hook(**hook_input['kwargs'])
19.79                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
19.79     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 112, in get_requires_for_build_wheel
19.79       backend = _build_backend()
19.79                 ^^^^^^^^^^^^^^^^
19.79     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 74, in _build_backend
19.79       ep = os.environ['PEP517_BUILD_BACKEND']
19.79            ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
19.79     File "<frozen os>", line 679, in __getitem__
19.79   KeyError: 'PEP517_BUILD_BACKEND'
19.79   
19.79 
19.79   at /usr/local/lib/python3.11/site-packages/poetry/installation/chef.py:166 in _prepare
19.85       162โ”‚ 
19.85       163โ”‚                 error = ChefBuildError("\n\n".join(message_parts))
19.85       164โ”‚ 
19.85       165โ”‚             if error is not None:
19.85     โ†’ 166โ”‚                 raise error from None
19.85       167โ”‚ 
19.86       168โ”‚             return path
19.86       169โ”‚ 
19.86       170โ”‚     def _prepare_sdist(self, archive: Path, destination: Path | None = None) -> Path:
19.87 
19.87 Note: This error originates from the build backend, and is likely not a problem with poetry but with jsmin (3.0.1) not supporting PEP 517 builds. You can verify this by running 'pip wheel --no-cache-dir --use-pep517 "jsmin (==3.0.1)"'.
19.87 
19.88 
19.88   ChefBuildError
19.88 
19.88   Backend subprocess exited when trying to invoke get_requires_for_build_wheel
19.88   
19.88   Traceback (most recent call last):
19.88     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
19.88       main()
19.88     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 335, in main
19.88       json_out['return_val'] = hook(**hook_input['kwargs'])
19.88                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
19.88     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 112, in get_requires_for_build_wheel
19.88       backend = _build_backend()
19.88                 ^^^^^^^^^^^^^^^^
19.88     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 74, in _build_backend
19.88       ep = os.environ['PEP517_BUILD_BACKEND']
19.88            ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
19.88     File "<frozen os>", line 679, in __getitem__
19.88   KeyError: 'PEP517_BUILD_BACKEND'
19.88   
19.88 
19.88   at /usr/local/lib/python3.11/site-packages/poetry/installation/chef.py:166 in _prepare
19.91       162โ”‚ 
19.91       163โ”‚                 error = ChefBuildError("\n\n".join(message_parts))
19.91       164โ”‚ 
19.91       165โ”‚             if error is not None:
19.91     โ†’ 166โ”‚                 raise error from None
19.91       167โ”‚ 
19.91       168โ”‚             return path
19.91       169โ”‚ 
19.91       170โ”‚     def _prepare_sdist(self, archive: Path, destination: Path | None = None) -> Path:
19.91 
19.91 Note: This error originates from the build backend, and is likely not a problem with poetry but with csscompressor (0.9.5) not supporting PEP 517 builds. You can verify this by running 'pip wheel --no-cache-dir --use-pep517 "csscompressor (==0.9.5)"'.
19.91 
19.91   โ€ข Installing pytest (8.2.0)
19.91   โ€ข Installing python-multipart (0.0.7)
19.91   โ€ข Installing pytz (2023.3.post1)
19.97 
19.98   ChefBuildError
19.98 
19.98   Backend subprocess exited when trying to invoke get_requires_for_build_wheel
19.98   
19.98   Traceback (most recent call last):
19.98     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
19.98       main()
19.98     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 335, in main
19.98       json_out['return_val'] = hook(**hook_input['kwargs'])
19.98                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
19.98     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 112, in get_requires_for_build_wheel
19.98       backend = _build_backend()
19.98                 ^^^^^^^^^^^^^^^^
19.98     File "/usr/local/lib/python3.11/site-packages/pyproject_hooks/_in_process/_in_process.py", line 74, in _build_backend
19.98       ep = os.environ['PEP517_BUILD_BACKEND']
19.98            ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
19.98     File "<frozen os>", line 679, in __getitem__
19.98   KeyError: 'PEP517_BUILD_BACKEND'
19.98   
19.98 
19.98   at /usr/local/lib/python3.11/site-packages/poetry/installation/chef.py:166 in _prepare
20.02       162โ”‚ 
20.02       163โ”‚                 error = ChefBuildError("\n\n".join(message_parts))
20.03       164โ”‚ 
20.03       165โ”‚             if error is not None:
20.03     โ†’ 166โ”‚                 raise error from None
20.03       167โ”‚ 
20.03       168โ”‚             return path
20.03       169โ”‚ 
20.03       170โ”‚     def _prepare_sdist(self, archive: Path, destination: Path | None = None) -> Path:
20.03 
20.03 Note: This error originates from the build backend, and is likely not a problem with poetry but with paginate (0.5.6) not supporting PEP 517 builds. You can verify this by running 'pip wheel --no-cache-dir --use-pep517 "paginate (==0.5.6)"'.
20.03 
20.03   โ€ข Installing regex (2023.12.25)
20.11   โ€ข Installing simple-toml-settings (0.6.1)
20.14   โ€ข Installing single-source (0.3.0)
20.31   โ€ข Installing sqlalchemy (2.0.29)
20.32   โ€ข Installing starlette (0.37.2)
20.38   โ€ข Installing termcolor (2.4.0)
20.45   โ€ข Downgrading tomlkit (0.12.5 -> 0.12.3)
20.55   โ€ข Downgrading trove-classifiers (2024.4.10 -> 2024.1.8)
20.55   โ€ข Installing typer (0.9.4)
20.62   โ€ข Installing ujson (5.9.0)
20.71   โ€ข Installing uvicorn (0.29.0)
20.75   โ€ข Downgrading virtualenv (20.26.1 -> 20.25.0)
------
failed to solve: process "/bin/sh -c poetry install" did not complete successfully: exit code: 1

Expected behavior
Image builds successfully.

Additional context
This is something about the build backend, this PEP-517 build stuff is a common error (See python-poetry/poetry#8287) but none of the fixes worked, except removing the create.venv = false stuff in the Dockerfile.
But then the image builds successfully, but crashes shortly (alembic not found)

Advanced User Management

Is your feature request related to a problem? Please describe.
It would be really nice to have a complete paginated CRUD management of Users, Roles, Groups, Permissions with the option to search.

Describe the solution you'd like
Possibility to create User with Roles/Groups with a set of Permissions, all previously created.

Describe alternatives you've considered
User can be created with a 'default' Role/Group but can be edited later on.

Cache Integration

Is your feature request related to a problem? Please describe.
For larger applications with a lot of data, caching architecture can increase greatly the performance of retrieving data.

Describe the solution you'd like
On the database query layer, first check if data exists on Redis, otherwise get on Postgres.

Docker Support

Is your feature request related to a problem? Please describe.
Add the possibility to run api+db on docker containers.

Describe the solution you'd like
Create a Dockerfile and docker-compose and provide the commands to run it.

Additional info
Forked the repo and already added this files. Also added Websec middlewares to improve security. (PR can be created)

Extra info
Nice idea creating the template, it can be very usefull if all right features are in place. Good job man!

Internal Links on the web documentation site are broken.

Describe the bug
Internal Links on the web documentation site are broken.

  • Some links use absolute paths which fail since the GitHub pages are served from a sub-directory.
  • The Relative paths look bolloxed too

We could use a CNAME and custom domain so everything is served from the root which should work. I have a couple of personal domains we can use.

Error when creating user from CLI

using ./api-admin user create from the command line results in the following error :

-> ERROR adding User : UserManager.register() missing 1 required positional argument: 'background_tasks'

This is due to the new email-sending functionality - it needs a background_tasks parameter which is not available on the CLI.

DB Connection / release error

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
multiple requests which hit the db simultaneously or in quick succession

Seeing error:

   |     user_data = await db.fetch_one(
   |   File "/usr/local/lib/python3.9/site-packages/databases/core.py", line 152, in fetch_one
   |     return await connection.fetch_one(query, values)
   |   File "/usr/local/lib/python3.9/site-packages/databases/core.py", line 251, in __aexit__
   |     await self._connection.release()
  |   File "/usr/local/lib/python3.9/site-packages/databases/backends/postgres.py", line 174, in release
 |     assert self._database._pool is not None, "DatabaseBackend is not running"
  | AssertionError: DatabaseBackend is not running

Projects generated from template fail tests d/t codacy key

Describe the bug
Projects generated from this template fail tests d/t Codacy key not existing. A simple Fork, however, should still work.

To Reproduce
Click the use this template button. Once the first commit is made, all tests fail at the upload coverage part because no CODACY key is set.

Expected behaviour
Test work out the box

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.