Common utils and services for FastAPI projects.
Project description
FastAPI Toolkit
A comprehensive toolkit providing common utilities, services, and components for FastAPI projects. This package includes authentication, database management, user management, and security utilities to accelerate FastAPI development.
Features
- 🔐 JWT Authentication: Complete JWT token management with access and refresh tokens
- 🍪 Cookie Management: Secure HTTP cookie handling for authentication
- 👤 User Management: User creation, authentication, and management services
- 🗄️ Database Integration: SQLAlchemy-based database services with connection pooling
- 🔒 Password Security: Argon2 password hashing with validation
- 📊 Pydantic Schemas: Pre-built schemas for common data structures
- 🔧 FastAPI Dependencies: Ready-to-use dependency injection components
- ⚡ Type Safety: Full type hints and mypy support
Installation
pip install fastapi-toolkit
Quick Start
1. Database Setup
from fastapi import FastAPI
from fastapi_toolkit.services import DatabaseService
from fastapi_toolkit.schemas import DBConfigs
from fastapi_toolkit.dependencies import init_db_dependency
app = FastAPI()
# Configure database
db_configs = DBConfigs(
db_uri="postgresql://user:password@localhost/dbname",
pool_size=10,
max_overflow=20
)
# Initialize database service
db_service = DatabaseService(db_configs)
init_db_dependency(db_service)
2. JWT Authentication Setup
from datetime import timedelta
from fastapi_toolkit.services import JWTService
from fastapi_toolkit.dependencies import init_jwt_service
# Configure JWT service
jwt_service = JWTService(
secret_key="your-secret-key",
access_token_lifetime=timedelta(minutes=15),
refresh_token_lifetime=timedelta(days=7),
algorithm="HS256"
)
# Initialize JWT dependency
init_jwt_service(jwt_service)
3. Using Dependencies
from fastapi_toolkit.dependencies import (
DBDependency,
UserServiceDependency,
is_authenticated_header
)
# Dependencies are ready to use in your FastAPI routes
Core Components
Services
DatabaseService
Manages SQLAlchemy database connections with built-in connection pooling:
from fastapi_toolkit.services import DatabaseService
from fastapi_toolkit.schemas import DBConfigs
configs = DBConfigs(
db_uri="sqlite:///./test.db",
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_recycle=1800
)
db_service = DatabaseService(configs, is_sqlite=True)
JWTService
Handles JWT token creation and validation:
from fastapi_toolkit.services import JWTService
from datetime import timedelta
jwt_service = JWTService(
secret_key="your-secret-key",
access_token_lifetime=timedelta(minutes=15),
refresh_token_lifetime=timedelta(days=7)
)
# Create tokens
access_token = jwt_service.get_access_token({"user_id": 1})
refresh_token = jwt_service.get_refresh_token({"user_id": 1})
# Decode tokens
payload = jwt_service.decode_token(access_token.token)
CookieService
Manages secure HTTP cookies for authentication:
from fastapi_toolkit.services import CookieService
from fastapi_toolkit.schemas import LoginTokens
cookie_service = CookieService(
access_token_lifetime=timedelta(minutes=15),
refresh_token_lifetime=timedelta(days=7)
)
# Create login response with cookies
tokens = LoginTokens(
access_token="...",
refresh_token="...",
csrf_token="..."
)
response = cookie_service.create_login_cookies_response(tokens)
UserService
Provides user management functionality:
from fastapi_toolkit.services import UserService
from fastapi_toolkit.schemas import User, SuperUser
# With database session
user_service = UserService(db_session)
# Create users
user = User(email="user@example.com", password="SecurePass123#", name="John Doe")
user_service.create_user(user)
# Query users
user = user_service.get_user_by_email("user@example.com")
exists = user_service.user_exists("user@example.com")
Models
Base Model
All models inherit from a base model with common fields:
from fastapi_toolkit.models import Base
class MyModel(Base):
__tablename__ = "my_table"
# id, created_at, updated_at are automatically included
User Model
Abstract user model that can be extended:
from fastapi_toolkit.models import User, SuperUserMixin
class AppUser(User, SuperUserMixin):
__tablename__ = "users"
# Additional fields can be added here
Security Utilities
Password Hashing
Secure password hashing with Argon2:
from fastapi_toolkit.utils import get_argon_hasher, validate_strong_password
hasher = get_argon_hasher()
# Hash password
password = "MySecurePassword123#"
validate_strong_password(password) # Validates strength
hashed = hasher.hash_value(password)
# Verify password
is_valid, needs_rehash = hasher.verify_value(hashed, password)
Dependencies
Pre-configured FastAPI dependencies for common operations:
from fastapi_toolkit.dependencies import (
DBDependency,
UserServiceDependency,
JWTServiceDependency,
CookieServiceDependency,
is_authenticated_header,
is_authenticated_cookie,
is_anonymous_header,
is_anonymous_cookie
)
Schemas
Pydantic schemas for data validation:
from fastapi_toolkit.schemas import (
User,
SuperUser,
DBConfigs,
LoginTokens,
JWTTokenPayload,
AccessToken,
RefreshToken
)
Password Validation
The toolkit includes strong password validation:
- Minimum 8 characters
- At least 1 lowercase letter
- At least 1 uppercase letter
- At least 1 digit
- At least 1 special character (@, #, $)
from fastapi_toolkit.utils import validate_strong_password
try:
password = validate_strong_password("WeakPass")
except ValueError as e:
print(e) # "Password must contain at least 1 digit"
Custom User Models
Extend the base User model for your application:
from fastapi_toolkit.models import User, SuperUserMixin
from fastapi_toolkit.services import UserService
from sqlalchemy.orm import mapped_column, Mapped
class AppUser(User, SuperUserMixin):
__tablename__ = "users"
# Add custom fields
phone: Mapped[str] = mapped_column(nullable=True)
avatar_url: Mapped[str] = mapped_column(nullable=True)
# Configure UserService to use custom model
UserService.set_user_model(AppUser)
Configuration Examples
PostgreSQL Configuration
from fastapi_toolkit.schemas import DBConfigs
configs = DBConfigs(
db_uri="postgresql://username:password@localhost:5432/mydb",
pool_size=20,
max_overflow=30,
pool_timeout=60,
pool_recycle=3600,
other_engine_configs={
"echo": False,
"pool_pre_ping": True
}
)
SQLite Configuration
configs = DBConfigs(db_uri="sqlite:///./app.db")
db_service = DatabaseService(configs, is_sqlite=True)
Requirements
- Python 3.12+
- FastAPI 0.118.0+
- SQLAlchemy 2.0.43+
- Pydantic 2.0+
- PyJWT 2.10.1+
- argon2-cffi 25.1.0+
- email-validator 2.3.0+
Development
Changelog
Version 1.0.0
- Initial release
- JWT authentication services
- Database connection management
- User management services
- Security utilities
- FastAPI dependencies
- Comprehensive test suite
Version 1.1.0
- Removed property
refreshfrom JWTTokenPayload
Version 1.2.0
- Added
samesiteandsecurearguments while creating login cookies for functioncreate_login_cookies_response.
Author
Abhay Pratap Singh
Built for the FastAPI community.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file aps_fastapi_toolkit-1.2.0.tar.gz.
File metadata
- Download URL: aps_fastapi_toolkit-1.2.0.tar.gz
- Upload date:
- Size: 11.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ec01ee0486f8f2983357fe994796fff9fba6c6ada419d379142acfc232b02a00
|
|
| MD5 |
3b5d557028b71de03b8bd0e7cf5cb91a
|
|
| BLAKE2b-256 |
e5354e10c49116ad0f21ee320fcfc03dc53f8be4c9714a17c59cb7b59b527716
|
File details
Details for the file aps_fastapi_toolkit-1.2.0-py3-none-any.whl.
File metadata
- Download URL: aps_fastapi_toolkit-1.2.0-py3-none-any.whl
- Upload date:
- Size: 16.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b9352f39181ffd4b2530e62ae10a67793f62c71cf7a6af850943fc91c842fe02
|
|
| MD5 |
fc6b6a76315d583823c083a19c42a107
|
|
| BLAKE2b-256 |
a966689401f364c71ea22f3b9ea3d346aecb91d29ad5f2e34e0aa0ca60cf3b58
|