Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Data validation using Python type hints
The little ASGI framework that shines. 🌟
The Database Toolkit for Python
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
- 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"],
)
- 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
- 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
-
Install FastAPI Users:
pip install fastapi-users[sqlalchemy]
-
Set up your FastAPI app and database connection.
-
Define your user models (User, UserCreate, UserUpdate, UserDB).
-
Configure authentication backends and strategies.
-
Create a FastAPIUsers instance and include its routers in your app.
-
Run your FastAPI application:
uvicorn main:app --reload
Competitor Comparisons
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.
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.
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.
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
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
FastAPI Users
Ready-to-use and customizable users management for FastAPI
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
- SQLAlchemy ORM async included
- MongoDB with Beanie ODM included
- 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
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):
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.
Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Data validation using Python type hints
The little ASGI framework that shines. 🌟
The Database Toolkit for Python
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.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot