# 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.
[](https://python.org)
[](https://fastapi.tiangolo.com)
## 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
```bash
pip install fastapi-toolkit
```
## Quick Start
### 1. Database Setup
```python
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
```python
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
```python
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:
```python
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:
```python
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:
```python
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:
```python
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:
```python
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:
```python
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:
```python
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:
```python
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:
```python
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 (@, #, $)
```python
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:
```python
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
```python
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
```python
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 `refresh` from JWTTokenPayload
### Version 1.2.0
- Added `samesite` and `secure` arguments while creating login
cookies for function `create_login_cookies_response`.
### Version 1.2.1
- Added `set_token_url` in dependencies import
### Version 1.2.2
- Minor enhancements
## Author
Abhay Pratap Singh
---
Built for the FastAPI community.
Raw data
{
"_id": null,
"home_page": null,
"name": "aps-fastapi-toolkit",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.12",
"maintainer_email": null,
"keywords": "fastapi, jwt, authentication, database, sqlalchemy, security",
"author": "Abhay Pratap Singh",
"author_email": null,
"download_url": "https://files.pythonhosted.org/packages/e8/04/14b5a478c079f60be31dca0cc03b2f4008841d91401b44b5a1b12b637e01/aps_fastapi_toolkit-1.2.2.tar.gz",
"platform": null,
"description": "# FastAPI Toolkit\n\nA 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.\n\n[](https://python.org)\n[](https://fastapi.tiangolo.com)\n\n## Features\n\n- \ud83d\udd10 **JWT Authentication**: Complete JWT token management with access and refresh tokens\n- \ud83c\udf6a **Cookie Management**: Secure HTTP cookie handling for authentication\n- \ud83d\udc64 **User Management**: User creation, authentication, and management services\n- \ud83d\uddc4\ufe0f **Database Integration**: SQLAlchemy-based database services with connection pooling\n- \ud83d\udd12 **Password Security**: Argon2 password hashing with validation\n- \ud83d\udcca **Pydantic Schemas**: Pre-built schemas for common data structures\n- \ud83d\udd27 **FastAPI Dependencies**: Ready-to-use dependency injection components\n- \u26a1 **Type Safety**: Full type hints and mypy support\n\n## Installation\n\n```bash\npip install fastapi-toolkit\n```\n\n## Quick Start\n\n### 1. Database Setup\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_toolkit.services import DatabaseService\nfrom fastapi_toolkit.schemas import DBConfigs\nfrom fastapi_toolkit.dependencies import init_db_dependency\n\napp = FastAPI()\n\n# Configure database\ndb_configs = DBConfigs(\n db_uri=\"postgresql://user:password@localhost/dbname\",\n pool_size=10,\n max_overflow=20\n)\n\n# Initialize database service\ndb_service = DatabaseService(db_configs)\ninit_db_dependency(db_service)\n```\n\n### 2. JWT Authentication Setup\n\n```python\nfrom datetime import timedelta\nfrom fastapi_toolkit.services import JWTService\nfrom fastapi_toolkit.dependencies import init_jwt_service\n\n# Configure JWT service\njwt_service = JWTService(\n secret_key=\"your-secret-key\",\n access_token_lifetime=timedelta(minutes=15),\n refresh_token_lifetime=timedelta(days=7),\n algorithm=\"HS256\"\n)\n\n# Initialize JWT dependency\ninit_jwt_service(jwt_service)\n```\n\n### 3. Using Dependencies\n\n```python\nfrom fastapi_toolkit.dependencies import (\n DBDependency,\n UserServiceDependency,\n is_authenticated_header\n)\n\n# Dependencies are ready to use in your FastAPI routes\n```\n\n## Core Components\n\n### Services\n\n#### DatabaseService\n\nManages SQLAlchemy database connections with built-in connection pooling:\n\n```python\nfrom fastapi_toolkit.services import DatabaseService\nfrom fastapi_toolkit.schemas import DBConfigs\n\nconfigs = DBConfigs(\n db_uri=\"sqlite:///./test.db\",\n pool_size=5,\n max_overflow=10,\n pool_timeout=30,\n pool_recycle=1800\n)\n\ndb_service = DatabaseService(configs, is_sqlite=True)\n```\n\n#### JWTService\n\nHandles JWT token creation and validation:\n\n```python\nfrom fastapi_toolkit.services import JWTService\nfrom datetime import timedelta\n\njwt_service = JWTService(\n secret_key=\"your-secret-key\",\n access_token_lifetime=timedelta(minutes=15),\n refresh_token_lifetime=timedelta(days=7)\n)\n\n# Create tokens\naccess_token = jwt_service.get_access_token({\"user_id\": 1})\nrefresh_token = jwt_service.get_refresh_token({\"user_id\": 1})\n\n# Decode tokens\npayload = jwt_service.decode_token(access_token.token)\n```\n\n#### CookieService\n\nManages secure HTTP cookies for authentication:\n\n```python\nfrom fastapi_toolkit.services import CookieService\nfrom fastapi_toolkit.schemas import LoginTokens\n\ncookie_service = CookieService(\n access_token_lifetime=timedelta(minutes=15),\n refresh_token_lifetime=timedelta(days=7)\n)\n\n# Create login response with cookies\ntokens = LoginTokens(\n access_token=\"...\",\n refresh_token=\"...\",\n csrf_token=\"...\"\n)\nresponse = cookie_service.create_login_cookies_response(tokens)\n```\n\n#### UserService\n\nProvides user management functionality:\n\n```python\nfrom fastapi_toolkit.services import UserService\nfrom fastapi_toolkit.schemas import User, SuperUser\n\n# With database session\nuser_service = UserService(db_session)\n\n# Create users\nuser = User(email=\"user@example.com\", password=\"SecurePass123#\", name=\"John Doe\")\nuser_service.create_user(user)\n\n# Query users\nuser = user_service.get_user_by_email(\"user@example.com\")\nexists = user_service.user_exists(\"user@example.com\")\n```\n\n### Models\n\n#### Base Model\n\nAll models inherit from a base model with common fields:\n\n```python\nfrom fastapi_toolkit.models import Base\n\nclass MyModel(Base):\n __tablename__ = \"my_table\"\n # id, created_at, updated_at are automatically included\n```\n\n#### User Model\n\nAbstract user model that can be extended:\n\n```python\nfrom fastapi_toolkit.models import User, SuperUserMixin\n\nclass AppUser(User, SuperUserMixin):\n __tablename__ = \"users\"\n # Additional fields can be added here\n```\n\n### Security Utilities\n\n#### Password Hashing\n\nSecure password hashing with Argon2:\n\n```python\nfrom fastapi_toolkit.utils import get_argon_hasher, validate_strong_password\n\nhasher = get_argon_hasher()\n\n# Hash password\npassword = \"MySecurePassword123#\"\nvalidate_strong_password(password) # Validates strength\nhashed = hasher.hash_value(password)\n\n# Verify password\nis_valid, needs_rehash = hasher.verify_value(hashed, password)\n```\n\n### Dependencies\n\nPre-configured FastAPI dependencies for common operations:\n\n```python\nfrom fastapi_toolkit.dependencies import (\n DBDependency,\n UserServiceDependency,\n JWTServiceDependency,\n CookieServiceDependency,\n is_authenticated_header,\n is_authenticated_cookie,\n is_anonymous_header,\n is_anonymous_cookie\n)\n```\n\n### Schemas\n\nPydantic schemas for data validation:\n\n```python\nfrom fastapi_toolkit.schemas import (\n User,\n SuperUser,\n DBConfigs,\n LoginTokens,\n JWTTokenPayload,\n AccessToken,\n RefreshToken\n)\n```\n\n## Password Validation\n\nThe toolkit includes strong password validation:\n\n- Minimum 8 characters\n- At least 1 lowercase letter\n- At least 1 uppercase letter \n- At least 1 digit\n- At least 1 special character (@, #, $)\n\n```python\nfrom fastapi_toolkit.utils import validate_strong_password\n\ntry:\n password = validate_strong_password(\"WeakPass\")\nexcept ValueError as e:\n print(e) # \"Password must contain at least 1 digit\"\n```\n\n## Custom User Models\n\nExtend the base User model for your application:\n\n```python\nfrom fastapi_toolkit.models import User, SuperUserMixin\nfrom fastapi_toolkit.services import UserService\nfrom sqlalchemy.orm import mapped_column, Mapped\n\nclass AppUser(User, SuperUserMixin):\n __tablename__ = \"users\"\n \n # Add custom fields\n phone: Mapped[str] = mapped_column(nullable=True)\n avatar_url: Mapped[str] = mapped_column(nullable=True)\n\n# Configure UserService to use custom model\nUserService.set_user_model(AppUser)\n```\n\n## Configuration Examples\n\n### PostgreSQL Configuration\n\n```python\nfrom fastapi_toolkit.schemas import DBConfigs\n\nconfigs = DBConfigs(\n db_uri=\"postgresql://username:password@localhost:5432/mydb\",\n pool_size=20,\n max_overflow=30,\n pool_timeout=60,\n pool_recycle=3600,\n other_engine_configs={\n \"echo\": False,\n \"pool_pre_ping\": True\n }\n)\n```\n\n### SQLite Configuration\n\n```python\nconfigs = DBConfigs(db_uri=\"sqlite:///./app.db\")\ndb_service = DatabaseService(configs, is_sqlite=True)\n```\n\n## Requirements\n\n- Python 3.12+\n- FastAPI 0.118.0+\n- SQLAlchemy 2.0.43+\n- Pydantic 2.0+\n- PyJWT 2.10.1+\n- argon2-cffi 25.1.0+\n- email-validator 2.3.0+\n\n## Development\n\n## Changelog\n\n### Version 1.0.0\n\n- Initial release\n- JWT authentication services\n- Database connection management\n- User management services\n- Security utilities\n- FastAPI dependencies\n- Comprehensive test suite\n\n### Version 1.1.0\n\n- Removed property `refresh` from JWTTokenPayload\n\n### Version 1.2.0\n\n- Added `samesite` and `secure` arguments while creating login\n cookies for function `create_login_cookies_response`.\n\n### Version 1.2.1\n\n- Added `set_token_url` in dependencies import\n\n### Version 1.2.2\n\n- Minor enhancements\n\n## Author\n\nAbhay Pratap Singh\n\n---\n\nBuilt for the FastAPI community.\n",
"bugtrack_url": null,
"license": null,
"summary": "Common utils and services for FastAPI projects.",
"version": "1.2.2",
"project_urls": null,
"split_keywords": [
"fastapi",
" jwt",
" authentication",
" database",
" sqlalchemy",
" security"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "d1e8181e337f03f11af271cca51cdd756e9d21a93b818d011fed6712e6ca59dc",
"md5": "e0f5302cf2655dabaf513533b167bf1d",
"sha256": "ea5079effdfa4fe48f950c2e107c5c49441d0e24f5e59044ea5290f8f4288bfc"
},
"downloads": -1,
"filename": "aps_fastapi_toolkit-1.2.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "e0f5302cf2655dabaf513533b167bf1d",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.12",
"size": 16378,
"upload_time": "2025-10-11T09:24:01",
"upload_time_iso_8601": "2025-10-11T09:24:01.021830Z",
"url": "https://files.pythonhosted.org/packages/d1/e8/181e337f03f11af271cca51cdd756e9d21a93b818d011fed6712e6ca59dc/aps_fastapi_toolkit-1.2.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "e80414b5a478c079f60be31dca0cc03b2f4008841d91401b44b5a1b12b637e01",
"md5": "5969fd1e44f95658afaaa8a696cb104a",
"sha256": "a71f339e3e7196c060526061820d70393d3fdba8fe202fbdb482453b2cce2775"
},
"downloads": -1,
"filename": "aps_fastapi_toolkit-1.2.2.tar.gz",
"has_sig": false,
"md5_digest": "5969fd1e44f95658afaaa8a696cb104a",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.12",
"size": 11427,
"upload_time": "2025-10-11T09:24:02",
"upload_time_iso_8601": "2025-10-11T09:24:02.124507Z",
"url": "https://files.pythonhosted.org/packages/e8/04/14b5a478c079f60be31dca0cc03b2f4008841d91401b44b5a1b12b637e01/aps_fastapi_toolkit-1.2.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-10-11 09:24:02",
"github": false,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"lcname": "aps-fastapi-toolkit"
}