Convert Figma logo to code with AI

fastapi-users logofastapi-users

Ready-to-use and customizable users management for FastAPI

4,991
411
4,991
25

Top Related Projects

82,358

FastAPI framework, high performance, easy to learn, fast to code, ready for production

22,955

Data validation using Python type hints

10,758

The little ASGI framework that shines. 🌟

The Database Toolkit for Python

11,838

Headless cloud-native authentication and identity management written in Go. Scales to a billion+ users. Replace Homegrown, Auth0, Okta, Firebase with better UX and DX. Passkeys, Social Sign In, OIDC, Magic Link, Multi-Factor Auth, SMS, SAML, TOTP, and more. Runs everywhere, runs best on Ory Network.

Quick Overview

FastAPI Users is a ready-to-use and customizable users management system for FastAPI. It provides a set of routes and models for handling user registration, authentication, and management, integrating seamlessly with FastAPI applications.

Pros

  • Easy to integrate with existing FastAPI projects
  • Supports multiple authentication backends (JWT, cookie, database)
  • Highly customizable with extensive configuration options
  • Includes features like password reset, email verification, and OAuth support

Cons

  • May be overkill for simple projects with basic user management needs
  • Learning curve for advanced customization
  • Dependency on specific database backends (SQLAlchemy, MongoDB, etc.)

Code Examples

  1. Basic setup with SQLAlchemy:
from fastapi import FastAPI
from fastapi_users import FastAPIUsers, models
from fastapi_users.authentication import AuthenticationBackend, BearerTransport, JWTStrategy
from fastapi_users.db import SQLAlchemyUserDatabase

app = FastAPI()

# Define user model and database
class User(models.BaseUser):
    pass

class UserCreate(models.BaseUserCreate):
    pass

class UserUpdate(models.BaseUserUpdate):
    pass

class UserDB(User, models.BaseUserDB):
    pass

# Setup authentication
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
jwt_strategy = JWTStrategy(secret="YOUR_JWT_SECRET", lifetime_seconds=3600)

auth_backend = AuthenticationBackend(
    name="jwt",
    transport=bearer_transport,
    get_strategy=jwt_strategy,
)

fastapi_users = FastAPIUsers(
    user_db,
    [auth_backend],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

# Include FastAPI Users routes
app.include_router(
    fastapi_users.get_auth_router(auth_backend),
    prefix="/auth/jwt",
    tags=["auth"],
)
app.include_router(
    fastapi_users.get_register_router(),
    prefix="/auth",
    tags=["auth"],
)
  1. Custom user model:
from fastapi_users import models

class User(models.BaseUser):
    first_name: str
    last_name: str

class UserCreate(models.BaseUserCreate):
    first_name: str
    last_name: str

class UserUpdate(models.BaseUserUpdate):
    first_name: Optional[str]
    last_name: Optional[str]

class UserDB(User, models.BaseUserDB):
    pass
  1. OAuth setup:
from fastapi_users.authentication import OAuth2AuthorizationCodeBearerTransport
from fastapi_users.oauth import GoogleOAuth2

google_oauth_client = GoogleOAuth2("CLIENT_ID", "CLIENT_SECRET")

oauth_transport = OAuth2AuthorizationCodeBearerTransport(
    authorize_url="/auth/oauth/google/authorize",
    token_url="/auth/oauth/google/callback",
)

fastapi_users = FastAPIUsers(
    user_db,
    [auth_backend, oauth_transport],
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

app.include_router(
    fastapi_users.get_oauth_router(google_oauth_client, auth_backend, "google"),
    prefix="/auth/oauth",
    tags=["auth"],
)

Getting Started

  1. Install FastAPI Users:

    pip install fastapi-users[sqlalchemy]
    
  2. Set up your FastAPI app and database connection.

  3. Define your user models (User, UserCreate, UserUpdate, UserDB).

  4. Configure authentication backends and strategies.

  5. Create a FastAPIUsers instance and include its routers in your app.

  6. Run your FastAPI application:

    uvicorn main:app --reload
    

Competitor Comparisons

82,358

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • More comprehensive and general-purpose web framework
  • Larger community and ecosystem, with more extensions and integrations
  • Extensive documentation and tutorials for various use cases

Cons of FastAPI

  • Requires more setup and configuration for user management features
  • Less opinionated, which may lead to more decision-making for developers

Code Comparison

FastAPI (basic route):

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

FastAPI-Users (user registration):

from fastapi_users import FastAPIUsers

fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

app.include_router(
    fastapi_users.get_register_router(),
    prefix="/auth",
    tags=["auth"],
)

FastAPI-Users is a specialized extension built on top of FastAPI, focusing on user management features. It provides pre-built routes and functionality for user registration, authentication, and profile management. FastAPI, on the other hand, is a more general-purpose web framework that offers flexibility and performance for building various types of APIs.

While FastAPI requires more manual setup for user-related features, it allows for greater customization and control over the implementation. FastAPI-Users simplifies user management but may be less flexible for complex or unique user scenarios.

22,955

Data validation using Python type hints

Pros of Pydantic

  • More general-purpose data validation and settings management
  • Extensive type hinting and IDE support
  • Broader ecosystem and integration with many Python libraries

Cons of Pydantic

  • Not specifically designed for user management in FastAPI
  • Requires more custom code for user-related functionality
  • Less out-of-the-box features for authentication and authorization

Code Comparison

Pydantic model example:

from pydantic import BaseModel, EmailStr

class User(BaseModel):
    id: int
    name: str
    email: EmailStr

FastAPI-Users model example:

from fastapi_users import models

class User(models.BaseUser):
    pass

FastAPI-Users provides a more opinionated and feature-rich user model out of the box, while Pydantic offers a flexible base for custom data models. FastAPI-Users is tailored for user management in FastAPI applications, including authentication and authorization features. Pydantic, on the other hand, is a general-purpose data validation library that can be used in various contexts beyond user management.

While Pydantic offers greater flexibility and wider applicability, FastAPI-Users provides a more streamlined experience for implementing user-related functionality in FastAPI projects. The choice between the two depends on the specific requirements of your project and the level of customization needed for user management.

10,758

The little ASGI framework that shines. 🌟

Pros of Starlette

  • Lightweight and flexible ASGI framework, providing a solid foundation for building web applications
  • Excellent performance and low overhead, suitable for high-performance applications
  • Extensive middleware support and WebSocket handling capabilities

Cons of Starlette

  • Lacks built-in user authentication and management features
  • Requires more manual setup and configuration for user-related functionality
  • Less opinionated, which may lead to more boilerplate code for common tasks

Code Comparison

Starlette:

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({"message": "Hello, World!"})

app = Starlette(routes=[Route("/", homepage)])

FastAPI-Users:

from fastapi import FastAPI
from fastapi_users import FastAPIUsers, models
from fastapi_users.authentication import JWTAuthentication

app = FastAPI()
fastapi_users = FastAPIUsers(
    user_model=models.BaseUser,
    auth_backends=[JWTAuthentication(secret="SECRET", lifetime_seconds=3600)],
)

app.include_router(fastapi_users.get_auth_router(), prefix="/auth/jwt", tags=["auth"])

While Starlette provides a lightweight foundation for building web applications, FastAPI-Users offers a more comprehensive solution for user management and authentication out of the box. Starlette requires more manual setup for user-related features, whereas FastAPI-Users provides pre-built components for common user management tasks.

The Database Toolkit for Python

Pros of SQLAlchemy

  • More comprehensive and flexible ORM with support for multiple databases
  • Mature project with extensive documentation and community support
  • Powerful query construction and optimization capabilities

Cons of SQLAlchemy

  • Steeper learning curve due to its extensive feature set
  • Can be overkill for simple projects or those focused on FastAPI integration
  • Requires more boilerplate code for basic operations

Code Comparison

SQLAlchemy:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

FastAPI Users:

from fastapi_users.db import SQLAlchemyBaseUserTable
from sqlalchemy import Column, Integer, String

class User(SQLAlchemyBaseUserTable):
    name = Column(String)

SQLAlchemy provides a more flexible and powerful ORM solution, suitable for complex database operations across various database systems. It offers advanced querying capabilities and extensive customization options. However, it comes with a steeper learning curve and may require more setup code.

FastAPI Users, on the other hand, is specifically designed for FastAPI integration and provides a more streamlined approach to user management. It offers out-of-the-box authentication and authorization features, making it easier to implement user-related functionality in FastAPI applications. However, it may be less flexible for complex database operations outside of user management.

11,838

Headless cloud-native authentication and identity management written in Go. Scales to a billion+ users. Replace Homegrown, Auth0, Okta, Firebase with better UX and DX. Passkeys, Social Sign In, OIDC, Magic Link, Multi-Factor Auth, SMS, SAML, TOTP, and more. Runs everywhere, runs best on Ory Network.

Pros of Kratos

  • More comprehensive identity and user management system
  • Language-agnostic, can be integrated with various tech stacks
  • Supports advanced features like multi-factor authentication and account recovery

Cons of Kratos

  • Steeper learning curve and more complex setup
  • Requires additional infrastructure (separate service)
  • May be overkill for smaller projects or simpler authentication needs

Code Comparison

FastAPI-Users:

from fastapi_users import FastAPIUsers

fastapi_users = FastAPIUsers(
    user_db,
    auth_backends,
    User,
    UserCreate,
    UserUpdate,
    UserDB,
)

app.include_router(
    fastapi_users.get_auth_router(auth_backends[0]),
    prefix="/auth/jwt",
    tags=["auth"],
)

Kratos:

version: v0.7.1-alpha.1

dsn: memory

serve:
  public:
    base_url: http://127.0.0.1:4433/
    cors:
      enabled: true
  admin:
    base_url: http://kratos:4434/

selfservice:
  strategies:
    password:
      enabled: true

FastAPI-Users is more tightly integrated with FastAPI and provides a simpler setup for basic authentication scenarios. Kratos offers a more robust and scalable solution but requires additional configuration and infrastructure. The choice between them depends on project requirements, scalability needs, and desired features.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

FastAPI Users

FastAPI Users

Ready-to-use and customizable users management for FastAPI

build codecov PyPI version Downloads

All Contributors

Subscribe


Documentation: https://fastapi-users.github.io/fastapi-users/

Source Code: https://github.com/fastapi-users/fastapi-users


Add quickly a registration and authentication system to your FastAPI project. FastAPI Users is designed to be as customizable and adaptable as possible.

Features

  • Extensible base user model
  • Ready-to-use register, login, reset password and verify e-mail routes
  • Ready-to-use social OAuth2 login flow
  • Dependency callables to inject current user in route
  • Pluggable password validation
  • Customizable database backend
  • Multiple customizable authentication backends
    • Transports: Authorization header, Cookie
    • Strategies: JWT, Database, Redis
  • Full OpenAPI schema support, even with several authentication backends

In a hurry? Discover Fief, the open-source authentication platform

Fief

Fief

Implementing registration, login, social auth is hard and painful. We know it. With our highly secure and open-source users management platform, you can focus on your app while staying in control of your users data.

  • Open-source: self-host it for free
  • Pre-built login and registration pages: clean and fast authentication so you don't have to do it yourself
  • Official Python client with built-in FastAPI integration

It's free and open-source

Contributors and sponsors ✨☕️

Thanks goes to these wonderful people (emoji key):

François Voron
François Voron

🚧
Paolo Dina
Paolo Dina

💵 💻
Dmytro Ohorodnik
Dmytro Ohorodnik

🐛
Matthew D. Scholefield
Matthew D. Scholefield

🐛 💻
roywes
roywes

🐛 💻
Satwik Kansal
Satwik Kansal

📖
Edd Salkield
Edd Salkield

💻 📖
mark-todd
mark-todd

💻 📖
lill74
lill74

🐛 💻 📖
SelfhostedPro
SelfhostedPro

🛡️ 💻
Oskar Gmerek
Oskar Gmerek

📖
Martin Collado
Martin Collado

🐛 💻
Eric Lopes
Eric Lopes

📖 🛡️
Beau Breon
Beau Breon

💻
Niyas Mohammed
Niyas Mohammed

📖
prostomarkeloff
prostomarkeloff

📖 💻
Marius Mézerette
Marius Mézerette

🐛 🤔
Nickolas Grigoriadis
Nickolas Grigoriadis

🐛
Open Data Coder
Open Data Coder

🤔
Mohammed Alshehri
Mohammed Alshehri

🤔
Tyler Renelle
Tyler Renelle

🤔
collerek
collerek

💻
Robert Bracco
Robert Bracco

💵
Augusto Herrmann
Augusto Herrmann

📖
Smithybrewer
Smithybrewer

🐛
silllli
silllli

📖
alexferrari88
alexferrari88

💵
sandalwoodbox
sandalwoodbox

🐛 📖
Vlad Hoi
Vlad Hoi

📖
Joe Nudell
Joe Nudell

🐛
Ben
Ben

💻
BoYanZh
BoYanZh

📖
David Brochart
David Brochart

📖 💻
Daan Beverdam
Daan Beverdam

💻
Stéphane Raimbault
Stéphane Raimbault

⚠️ 🐛
Sondre Lillebø Gundersen
Sondre Lillebø Gundersen

📖
Maxim
Maxim

📖 🐛
scottdavort
scottdavort

💵
John Dukewich
John Dukewich

📖
Yasser Tahiri
Yasser Tahiri

💻
Brandon H. Goding
Brandon H. Goding

💻 📖
PovilasK
PovilasK

💻
Just van den Broecke
Just van den Broecke

💵
jakemanger
jakemanger

🐛 💻
Ikko Ashimine
Ikko Ashimine

💻
Matyáš Richter
Matyáš Richter

💻
Hazedd
Hazedd

🐛 📖
Luis Roel
Luis Roel

💵
Alexandr Makurin
Alexandr Makurin

💻 🐛
Leon Thurner
Leon Thurner

📖
Goran Mekić
Goran Mekić

📦
Gaganpreet
Gaganpreet

💻
Joe Taylor
Joe Taylor

💻
Richard Friberg
Richard Friberg

🐛
Kenton Parton
Kenton Parton

💵
Adrian Ciołek
Adrian Ciołek

🐛
⭕Alexander Rymdeko-Harvey
⭕Alexander Rymdeko-Harvey

📖
schwannden
schwannden

🚧 💻
Jimmy Angel Pérez Díaz
Jimmy Angel Pérez Díaz

🛡️
Austin Orr
Austin Orr

🚧
Carlo Eugster
Carlo Eugster

🛡️
Vittorio Zamboni
Vittorio Zamboni

💻
Andrey
Andrey

📖
Can H. Tartanoglu
Can H. Tartanoglu

🐛
Filipe Nascimento
Filipe Nascimento

🛡️
dudulu
dudulu

💵 🐛 💬
Toni Alatalo
Toni Alatalo

💻 📖
Börge Kiss
Börge Kiss

📖
Guilherme Caminha
Guilherme Caminha

📖
Téva KRIEF
Téva KRIEF

💻
Essa Alshammri
Essa Alshammri

📖
0xJan
0xJan

🐛
Justin Thomas
Justin Thomas

💻
Adam Israel
Adam Israel

💻
Nerixjk
Nerixjk

🐛 💻
Mike Fotinakis
Mike Fotinakis

💻 🐛
lifengmds
lifengmds

💵
raindata5
raindata5

📖
Mark Donnelly
Mark Donnelly

📖
Alexander Zinov
Alexander Zinov

💻
nimaxin
nimaxin

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Development

Setup environment

We use Hatch to manage the development environment and production build. Ensure it's installed on your system.

Run unit tests

You can run all the tests with:

hatch run test:test

Format the code

Execute the following command to apply linting and check typing:

hatch run lint

Serve the documentation

You can serve the documentation locally with the following command:

hatch run docs

The documentation will be available on http://localhost:8000.

License

This project is licensed under the terms of the MIT license.