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

...
You might also like...
Sample project showing reliable data ingestion application using FastAPI and dramatiq
Sample project showing reliable data ingestion application using FastAPI and dramatiq

Create and deploy a reliable data ingestion service with FastAPI, SQLModel and Dramatiq This is the source code for the data ingestion service explain

Lazy package to start your project using FastAPI✨
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:

Generate Class & Decorators for your FastAPI project ✨🚀

Classes and Decorators to use FastAPI with class based routing. In particular this allows you to construct an instance of a class and have methods of that instance be route handlers for FastAPI & Python 3.8.

Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker.

FastAPI + SQLModel + Alembic Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker. Want to learn how to build th

 FastAPI Project Template
FastAPI Project Template

The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

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

A dynamic FastAPI router that automatically creates CRUD routes for your models
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

Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

Opinionated set of utilities on top of FastAPI

FastAPI Contrib Opinionated set of utilities on top of FastAPI Free software: MIT license Documentation: https://fastapi-contrib.readthedocs.io. Featu

Comments
  • Implement Repository pattern

    Implement Repository pattern

    You can segregate the queries from view.py and put it in a repository. Use interface and implement in repository. The service layer is going to communicate with the database through the interface and repository.

    opened by SazidAhmed 1
Owner
Oluwaseyifunmi Oyefeso
A passionate self taught software developer.
Oluwaseyifunmi Oyefeso
FastAPI native extension, easy and simple JWT auth

fastapi-jwt FastAPI native extension, easy and simple JWT auth

Konstantin Chernyshev 19 Dec 12, 2022
:rocket: CLI tool for FastAPI. Generating new FastAPI projects & boilerplates made easy.

Project generator and manager for FastAPI. Source Code: View it on Github Features ?? Creates customizable project boilerplate. Creates customizable a

Yagiz Degirmenci 1k Jan 2, 2023
Simple FastAPI Example : Blog API using FastAPI : Beginner Friendly

fastapi_blog FastAPI : Simple Blog API with CRUD operation Steps to run the project: git clone https://github.com/mrAvi07/fastapi_blog.git cd fastapi-

Avinash Alanjkar 1 Oct 8, 2022
Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI

FastAPI Ariadne Example Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI - GitHub ###Запуск на локальном окру

ZeBrains Team 9 Nov 10, 2022
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
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 1, 2022
FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management

FastAPI Server-sided Session FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management.

DevGuyAhnaf 5 Dec 23, 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 5, 2022
Fastapi-ml-template - Fastapi ml template with python

FastAPI ML Template Run Web API Local $ sh run.sh # poetry run uvicorn app.mai

Yuki Okuda 29 Nov 20, 2022
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