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
Toolkit for developing and maintaining ML models

modelkit Python framework for production ML systems. modelkit is a minimalist yet powerful MLOps library for Python, built for people who want to depl

140 Dec 27, 2022
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.3k Dec 31, 2022
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

Tomasz Wójcik 300 Dec 26, 2022
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
Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.

Supported tags and respective Dockerfile links python3.8, latest (Dockerfile) python3.7, (Dockerfile) python3.6 (Dockerfile) python3.8-slim (Dockerfil

Sebastián Ramírez 2.1k Dec 31, 2022
Flask-vs-FastAPI - Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks.

Flask-vs-FastAPI Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks. IntroductionIn Flask is a popular mic

Mithlesh Navlakhe 1 Jan 01, 2022
A utility that allows you to use DI in fastapi without Depends()

fastapi-better-di What is this ? fastapi-better-di is a utility that allows you to use DI in fastapi without Depends() Installation pip install fastap

Maxim 9 May 24, 2022
FastAPI client generator

FastAPI-based API Client Generator Generate a mypy- and IDE-friendly API client from an OpenAPI spec. Sync and async interfaces are both available Com

David Montague 283 Jan 04, 2023
Qwerkey is a social media platform for connecting and learning more about mechanical keyboards built on React and Redux in the frontend and Flask in the backend on top of a PostgreSQL database.

Flask React Project This is the backend for the Flask React project. Getting started Clone this repository (only this branch) git clone https://github

Peter Mai 22 Dec 20, 2022
Opinionated authorization package for FastAPI

FastAPI Authorization Installation pip install fastapi-authorization Usage Currently, there are two models available: RBAC: Role-based Access Control

Marcelo Trylesinski 18 Jul 04, 2022
API Simples com python utilizando a biblioteca FastApi

api-fastapi-python API Simples com python utilizando a biblioteca FastApi Para rodar esse script são necessárias duas bibliotecas: Fastapi: Comando de

Leonardo Grava 0 Apr 29, 2022
Lightning FastAPI

Lightning FastAPI Lightning FastAPI framework, provides boiler plates for FastAPI based on Django Framework Explaination / | │ manage.py │ README.

Rajesh Joshi 1 Oct 15, 2021
API for Submarino store

submarino-api API for the submarino e-commerce documentation read the documentation in: https://submarino-api.herokuapp.com/docs or in https://submari

Miguel 1 Oct 14, 2021
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
Dead-simple mailer micro-service for static websites

Mailer Dead-simple mailer micro-service for static websites A free and open-source software alternative to contact form services such as FormSpree, to

Romain Clement 42 Dec 21, 2022
Easily integrate socket.io with your FastAPI app 🚀

fastapi-socketio Easly integrate socket.io with your FastAPI app. Installation Install this plugin using pip: $ pip install fastapi-socketio Usage To

Srdjan Stankovic 210 Dec 23, 2022
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
스타트업 개발자 채용

스타트업 개발자 채용 大 박람회 Seed ~ Series B에 있는 스타트업을 위한 채용정보 페이지입니다. Back-end, Frontend, Mobile 등 개발자를 대상으로 진행하고 있습니다. 해당 스타트업에 종사하시는 분뿐만 아니라 채용 관련 정보를 알고 계시다면

JuHyun Lee 58 Dec 14, 2022
FastAPI + Postgres + Docker Compose + Heroku Deploy Template

FastAPI + Postgres + Docker Compose + Heroku Deploy ⚠️ For educational purpose only. Not ready for production use YET Features FastAPI with Postgres s

DP 12 Dec 27, 2022
fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability

FastAPI2 Admin Introduction fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability. Now

Glib 14 Dec 05, 2022