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
A simple Blogging Backend app created with Fast API

This is a simple blogging app backend built with FastAPI. This project is created to simulate a real CRUD blogging system. It is built to be used by s

Owusu Kelvin Clark 13 Mar 24, 2022
A FastAPI WebSocket application that makes use of ncellapp package by @hemantapkh

ncellFastAPI author: @awebisam Used FastAPI to create WS application. Ncellapp module by @hemantapkh NOTE: Not following best practices and, needs ref

Aashish Bhandari 7 Oct 01, 2021
FastAPI CRUD template using Deta Base

Deta Base FastAPI CRUD FastAPI CRUD template using Deta Base Setup Install the requirements for the CRUD: pip3 install -r requirements.txt Add your D

Sebastian Ponce 2 Dec 15, 2021
Code Specialist 27 Oct 16, 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
Fastapi performans monitoring

Fastapi-performans-monitoring This project is a simple performance monitoring for FastAPI. License This project is licensed under the terms of the MIT

bilal alpaslan 11 Dec 31, 2022
A Sample App to Demonstrate React Native and FastAPI Integration

React Native - Service Integration with FastAPI Backend. A Sample App to Demonstrate React Native and FastAPI Integration UI Based on NativeBase toolk

YongKi Kim 4 Nov 17, 2022
Redis-based rate-limiting for FastAPI

Redis-based rate-limiting for FastAPI

Glib 6 Nov 14, 2022
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
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 04, 2023
Sample-fastapi - A sample app using Fastapi that you can deploy on App Platform

Getting Started We provide a sample app using Fastapi that you can deploy on App

Erhan BÜTE 2 Jan 17, 2022
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
High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (w/ Redis and PostgreSQL).

fastapi-gino-arq-uvicorn High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (powered by Redis & PostgreSQL). Contents Get Star

Leo Sussan 351 Jan 04, 2023
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
Ready-to-use and customizable users management for FastAPI

FastAPI Users Ready-to-use and customizable users management for FastAPI Documentation: https://fastapi-users.github.io/fastapi-users/ Source Code: ht

FastAPI Users 2.3k Dec 30, 2022
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 562 Jan 01, 2023
Keycloack plugin for FastApi.

FastAPI Keycloack Keycloack plugin for FastApi. Your aplication receives the claims decoded from the access token. Usage Run keycloak on port 8080 and

Elber 4 Jun 24, 2022
This project shows how to serve an ONNX-optimized image classification model as a web service with FastAPI, Docker, and Kubernetes.

Deploying ML models with FastAPI, Docker, and Kubernetes By: Sayak Paul and Chansung Park This project shows how to serve an ONNX-optimized image clas

Sayak Paul 104 Dec 23, 2022
FastAPI framework plugins

Plugins for FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi-plugins FastAPI framework plugins Cache Mem

RES 239 Dec 28, 2022
FastAPI backend for Repost

Repost FastAPI This is the FastAPI implementation of the Repost API. Installation Python 3 must be installed and accessible through the use of a termi

PC 7 Jun 15, 2021