FastAPI Auth Starter Project

Overview

FastAPI Auth Starter Project

This is a template for FastAPI that comes with authentication preconfigured.

Technology used

  • FastAPI
  • PostgreSQL
  • SQLAlchemy
  • Alembic

Use the template

Clone the repository

git clone https://github.com/sheyzi/fastapi_auth.git

Rename the project

mv fastapi_auth my_new_project

Change project name in core/settings.py

...

class Settings(BaseModel):
    PROJECT_TITLE: str = 'New Project name' # Updated
    PROJECT_VERSION: str = '1.0.0'

...

Create and activate virtual environment

python -m venv venv
source venv/bin/activate

Install dependencies

pip install -r requirements.txt

Rename sample.env to .env

mv sample.env .env

Get Deta project key

  • Open Deta.sh
  • Create an account or login
  • In your dashboard click the back arrow beside the deta logo at the top left
  • Click on the new project button
  • Name your project and select a region
  • Copy your project id and project key
  • Replace the one in the .env file with the one you had just created

Change secret key

>> import secrets >>> secrets.token_hex() '54e07b3ccd9f38e8601bd01d22537762dcff2c77957b2413ecf97e07e89e815e' >>>">
$ python
Python 3.8.10 (default, Nov 26 2021, 20:14:08)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import secrets
>>> secrets.token_hex()
'54e07b3ccd9f38e8601bd01d22537762dcff2c77957b2413ecf97e07e89e815e'
>>>

Replace the secret key in the .env file with the generated one

Configure database

Change the postgres sql information with their respective details in the .env file

Migrate the database

alembic upgrade head

Delete the current git repository

rm -rf .git

Run the project

python -m uvicorn main:app --reload

Open api docs

Navigate to 127.0.0.1:8000/docs

Add field to user model

The template comes without a username field, I will show you how to add that now!

  • Edit the models/users.py to add the username field
...

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, nullable=False, unique=True, index=True)
    username = Column(String, nullable=False) # New

...
  • Reflect db changes on the pydantic schema in the schemas/users.py
...

class UserBase(BaseModel):
    email: str
    username: str #New

...
  • Migrate the database
$ alembic revision --autogenerate -m "Added username field to users"
$ alembic upgrade head

Steps to add field to the users db

  • Edit the models/users.py file
  • Reflect changes in schemas/users.py file
  • Migrate database

How to use the authentication

  • Import the get_active_users dependency from the core/dependency.py
from core.dependency import get_active_user
  • Import the Depends function from fastapi
from fastapi import Depends
  • Import the UserOut class from the schemas/users.py
from schemas.users import UserOut
  • Add the dependency to the route function
...

@auth_router.post("/some-route/")
def register_user(current_user: UserOut = Depends(get_active_user)):

...

How to create custom auth permissions

In this section we will create a permission for only admins

In core/dependency.py add

...

def get_admin_user(current_user: UserOut = Depends(get_active_user)):
    if not current_user.is_admin:
        raise HTTPException("Not an admin user!")
    return current_user

...
Owner
Oluwaseyifunmi Oyefeso
A passionate self taught software developer.
Oluwaseyifunmi Oyefeso
🚀 Cookiecutter Template for FastAPI + React Projects. Using PostgreSQL, SQLAlchemy, and Docker

FastAPI + React · A cookiecutter template for bootstrapping a FastAPI and React project using a modern stack. Features FastAPI (Python 3.8) JWT authen

Gabriel Abud 1.4k Jan 02, 2023
Cookiecutter API for creating Custom Skills for Azure Search using Python and Docker

cookiecutter-spacy-fastapi Python cookiecutter API for quick deployments of spaCy models with FastAPI Azure Search The API interface is compatible wit

Microsoft 379 Jan 03, 2023
A minimum reproducible repository for embedding panel in FastAPI

FastAPI-Panel A minimum reproducible repository for embedding panel in FastAPI Follow either This Tutorial or These steps below ↓↓↓ Clone the reposito

Tyler Houssian 15 Sep 22, 2022
FastAPI Auth Starter Project

This is a template for FastAPI that comes with authentication preconfigured.

Oluwaseyifunmi Oyefeso 6 Nov 13, 2022
A dynamic FastAPI router that automatically creates CRUD routes for your models

âš¡ Create CRUD routes with lighting speed âš¡ A dynamic FastAPI router that automatically creates CRUD routes for your models Documentation: https://fast

Adam Watkins 943 Jan 01, 2023
Simple notes app backend using Python's FastAPI framework.

my-notes-app Simple notes app backend using Python's FastAPI framework. Route "/": User login (GET): return 200, list of all of their notes; User sign

José Gabriel Mourão Bezerra 2 Sep 17, 2022
CLI and Streamlit applications to create APIs from Excel data files within seconds, using FastAPI

FastAPI-Wrapper CLI & APIness Streamlit App Arvindra Sehmi, Oxford Economics Ltd. | Website | LinkedIn (Updated: 21 April, 2021) fastapi-wrapper is mo

Arvindra 49 Dec 03, 2022
Light, Flexible and Extensible ASGI API framework

Starlite Starlite is a light and flexible ASGI API framework. Using Starlette and pydantic as foundations. Check out the Starlite documentation 📚 Cor

1.5k Jan 04, 2023
A FastAPI Middleware of joerick/pyinstrument to check your service performance.

fastapi_profiler A FastAPI Middleware of joerick/pyinstrument to check your service performance. 📣 Info A FastAPI Middleware of pyinstrument to check

LeoSun 107 Jan 05, 2023
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 871 Dec 25, 2022
fastapi-mqtt is extension for MQTT protocol

fastapi-mqtt MQTT is a lightweight publish/subscribe messaging protocol designed for M2M (machine to machine) telemetry in low bandwidth environments.

Sabuhi 144 Dec 28, 2022
Docker Sample Project - FastAPI + NGINX

Docker Sample Project - FastAPI + NGINX Run FastAPI and Nginx using Docker container Installation Make sure Docker is installed on your local machine

1 Feb 11, 2022
A minimal Streamlit app showing how to launch and stop a FastAPI process on demand

Simple Streamlit + FastAPI Integration A minimal Streamlit app showing how to launch and stop a FastAPI process on demand. The FastAPI /run route simu

Arvindra 18 Jan 02, 2023
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

Steve Hillier 225 Jan 05, 2023
Restful Api developed with Flask using Prometheus and Grafana for monitoring and containerization with Docker :rocket:

Hephaestus 🚀 In Greek mythology, Hephaestus was either the son of Zeus and Hera or he was Hera's parthenogenous child. ... As a smithing god, Hephaes

Yasser Tahiri 16 Oct 07, 2022
Lazy package to start your project using FastAPI✨

Fastapi-lazy 🦥 Utilities that you use in various projects made in FastAPI. Source Code: https://github.com/yezz123/fastapi-lazy Install the project:

Yasser Tahiri 95 Dec 29, 2022
Farlimit - FastAPI rate limit with python

FastAPIRateLimit Contributing is F&E (free&easy) Y Usage pip install farlimit N

omid 27 Oct 06, 2022
Cache-house - Caching tool for python, working with Redis single instance and Redis cluster mode

Caching tool for python, working with Redis single instance and Redis cluster mo

Tural 14 Jan 06, 2022
FastAPI-PostgreSQL-Celery-RabbitMQ-Redis bakcend with Docker containerization

FastAPI - PostgreSQL - Celery - Rabbitmq backend This source code implements the following architecture: All the required database endpoints are imple

Juan Esteban Aristizabal 54 Nov 26, 2022
Get MODBUS data from Sofar (K-TLX) inverter through LSW-3 or LSE module

SOFAR Inverter + LSW-3/LSE Small utility to read data from SOFAR K-TLX inverters through the Solarman (LSW-3/LSE) datalogger. Two scripts to get inver

58 Dec 29, 2022