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
CURSO PROMETHEUS E GRAFANA: Observability in a real world

Curso de monitoração com o Prometheus Esse curso ensina como usar o Prometheus como uma ferramenta integrada de monitoração, entender seus conceitos,

Rafael Cirolini 318 Dec 23, 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
This code generator creates FastAPI app from an openapi file.

fastapi-code-generator This code generator creates FastAPI app from an openapi file. This project is an experimental phase. fastapi-code-generator use

Koudai Aono 632 Jan 05, 2023
FastAPI-Amis-Admin is a high-performance, efficient and easily extensible FastAPI admin framework. Inspired by django-admin, and has as many powerful functions as django-admin.

简体中文 | English 项目介绍 FastAPI-Amis-Admin fastapi-amis-admin是一个拥有高性能,高效率,易拓展的fastapi管理后台框架. 启发自Django-Admin,并且拥有不逊色于Django-Admin的强大功能. 源码 · 在线演示 · 文档 · 文

AmisAdmin 318 Dec 31, 2022
Hyperlinks for pydantic models

Hyperlinks for pydantic models In a typical web application relationships between resources are modeled by primary and foreign keys in a database (int

Jaakko Moisio 10 Apr 18, 2022
Easy and secure implementation of Azure AD for your FastAPI APIs 🔒

FastAPI-Azure-auth Azure AD Authentication for FastAPI apps made easy. 🚀 Description FastAPI is a modern, fast (high-performance), web framework for

Intility 216 Dec 27, 2022
Basic fastapi blockchain - An api based blockchain with full functionality

Basic fastapi blockchain - An api based blockchain with full functionality

1 Nov 27, 2021
api versioning for fastapi web applications

fastapi-versioning api versioning for fastapi web applications Installation pip install fastapi-versioning Examples from fastapi import FastAPI from f

Dean Way 472 Jan 02, 2023
Formatting of dates and times in Flask templates using moment.js.

Flask-Moment This extension enhances Jinja2 templates with formatting of dates and times using moment.js. Quick Start Step 1: Initialize the extension

Miguel Grinberg 358 Nov 28, 2022
Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ⭐

FRDP Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ⛏ . Getting Started Fe

BnademOverflow 53 Dec 29, 2022
A simple Redis Streams backed Chat app using Websockets, Asyncio and FastAPI/Starlette.

redis-streams-fastapi-chat A simple demo of Redis Streams backed Chat app using Websockets, Python Asyncio and FastAPI/Starlette. Requires Python vers

ludwig404 135 Dec 19, 2022
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
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 03, 2023
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
Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡

csrf-starlette-fastapi Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡ Will work with either a input type="hidden" field or ajax

Nathaniel Sabanski 9 Nov 20, 2022
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 310 Dec 14, 2022
FastAPI IPyKernel Sandbox

FastAPI IPyKernel Sandbox This repository is a light-weight FastAPI project that is meant to provide a wrapper around IPyKernel interactions. It is in

Nick Wold 2 Oct 25, 2021
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python Examples. The beyonic APIs Doc Reference: https://apidocs.beyonic.com/ To start using the Beyonic API Python API, you need to start

Harun Mbaabu Mwenda 46 Sep 01, 2022
flask extension for integration with the awesome pydantic package

flask extension for integration with the awesome pydantic package

249 Jan 06, 2023
Deploy/View images to database sqlite with fastapi

Deploy/View images to database sqlite with fastapi cd realistic Dependencies dat

Fredh Macau 1 Jan 04, 2022