Skip to main content

FastAPI Mason is a library for building FastAPI applications with a Django REST Framework-inspired architecture.

This project has been archived.

The maintainers of this project have marked this project as archived. No new releases are expected.

Project description

FastAPI Mason

logo

FastAPI Mason

Django REST Framework-inspired ViewSets and utilities for FastAPI applications with Tortoise ORM

PyPi Version Supported Python Versions License


Django REST Framework-inspired ViewSets and utilities for FastAPI applications with Tortoise ORM.

FastAPI Mason brings the beloved patterns and conventions from Django REST Framework to FastAPI, providing a structured and efficient way to build REST APIs. With familiar concepts like ViewSets, permissions, pagination, and serialization, you can rapidly develop robust API applications.

Just like skilled masons who craft solid foundations with precision and expertise, FastAPI Mason helps you build reliable, well-structured APIs with time-tested patterns and best practices.


Documentation: bubaley.github.io/fastapi-mason


📦 Installation

Install FastAPI Mason using UV:

uv add fastapi-mason

🚀 Quick Example

Here's a complete example showing how to build a REST API with FastAPI Mason:

# main.py - Complete FastAPI Mason application
from fastapi import APIRouter, FastAPI
from tortoise import fields
from tortoise.contrib.fastapi import register_tortoise
from tortoise.models import Model

from fastapi_mason.decorators import action, viewset
from fastapi_mason.pagination import PageNumberPagination
from fastapi_mason.schemas import SchemaMeta, generate_schema, rebuild_schema
from fastapi_mason.viewsets import ModelViewSet
from fastapi_mason.wrappers import PaginatedResponseDataWrapper, ResponseDataWrapper

# Database setup
def register_database(app: FastAPI):
    register_tortoise(
        app,
        db_url='sqlite://db.sqlite3',
        modules={'models': ['main']},
        generate_schemas=True,
        add_exception_handlers=True,
    )

# Models
class Company(Model):
    id = fields.IntField(primary_key=True)
    name = fields.CharField(max_length=255)
    full_name = fields.TextField(null=True)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)

# Schema meta
class CompanyMeta(SchemaMeta):
    include = ('id', 'name', 'full_name', 'created_at', 'updated_at')

# Schemas
CompanySchema = generate_schema(Company, meta=CompanyMeta)
CompanyCreateSchema = rebuild_schema(CompanySchema, exclude_readonly=True)

# Views
router = APIRouter(prefix='/companies', tags=['companies'])

@viewset(router)
class CompanyViewSet(ModelViewSet[Company]):
    model = Company
    read_schema = CompanySchema
    create_schema = CompanyCreateSchema

    pagination = PageNumberPagination
    list_wrapper = PaginatedResponseDataWrapper
    single_wrapper = ResponseDataWrapper

    # permission_classes = [IsAuthenticatedOrReadOnly]

    @action(methods=['GET'], detail=False, response_model=dict[str, int])
    async def stats(self):
        return {'total': await Company.all().count()}

# Application
app = FastAPI(title='My API')
register_database(app)
app.include_router(router)

Start server:

uvicorn main:app --reload

Try API Endpoints:

"""
This creates the following endpoints:
- GET /companies/ - List companies with pagination
- POST /companies/ - Create new company
- GET /companies/{item_id}/ - Get specific company
- PUT /companies/{item_id}/ - Update company
- DELETE /companies/{item_id}/ - Delete company
- GET /companies/stats/ - Custom stats endpoint

Example API Responses:

GET /companies/ (with pagination wrapper):
{
  "data": [
    {
      "id": 1,
      "name": "Acme Corp",
      "full_name": "Acme Corporation Ltd.",
      "created_at": "2023-01-01T10:00:00Z",
      "updated_at": "2023-01-01T10:00:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "page_size": 10,
    "total_pages": 5,
    "total_items": 47
  }
}

GET /companies/1/ (with single wrapper):
{
  "data": {
    "id": 1,
    "name": "Acme Corp",
    "full_name": "Acme Corporation Ltd.",
    "created_at": "2023-01-01T10:00:00Z",
    "updated_at": "2023-01-01T10:00:00Z"
  }
}

GET /companies/stats/ (custom action):
{
  "total": 123
}
"""

✨ Key Features

🎯 ViewSets

Django-like ViewSets with automatic CRUD operations and custom actions. Build complete REST APIs with minimal boilerplate code.

🔒 Permissions

Built-in permission system with customizable access control. Protect your endpoints with authentication and authorization rules.

📄 Pagination

Multiple pagination strategies out of the box: Limit/Offset and Page Number. You can easily customize or override pagination classes to suit your needs.

📋 Schema Generation

Intelligent schema generation with meta classes for fine-grained control over API serialization.

🔄 Response Wrappers

Consistent API response formatting with customizable wrapper classes.

⚡ State Management

Request-scoped state management for sharing data across middleware and view components.

🎯 Philosophy

FastAPI Mason is designed with these principles in mind:

  • Familiar: If you know Django REST Framework, you already know FastAPI Mason
  • Flexible: Customize every aspect while maintaining sensible defaults
  • Fast: Built on FastAPI's high-performance foundation
  • Modular: Use only what you need, when you need it

📚 Getting Started

Ready to build amazing APIs? Start with our Quick Start guide to get up and running in minutes.

Want to dive deeper? Explore our comprehensive guides:

🤝 Community

FastAPI Mason is open source and welcomes contributions! Whether you're reporting bugs, suggesting features, or submitting pull requests, your involvement helps make the library better for everyone.

📄 License

FastAPI Mason is released under the MIT License.

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

fastapi_mason-0.1.3.tar.gz (501.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_mason-0.1.3-py3-none-any.whl (20.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_mason-0.1.3.tar.gz.

File metadata

  • Download URL: fastapi_mason-0.1.3.tar.gz
  • Upload date:
  • Size: 501.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.20

File hashes

Hashes for fastapi_mason-0.1.3.tar.gz
Algorithm Hash digest
SHA256 4a99640cedf55f13810bddda87c1a524b25fd443fb128e43fe3fb0278815d033
MD5 dd7d18b71e0120b3ded13d3e8edd2f7c
BLAKE2b-256 d2af11fb7d553f1f641332becfe4e1559777b2c719f6ab46cab95d19bf8d3156

See more details on using hashes here.

File details

Details for the file fastapi_mason-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_mason-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9109f7bffee5847670422d7a42d42a79494387702159cb9301f2db87d2fd5c7b
MD5 db79e834025e23b11ece8c19257be0dd
BLAKE2b-256 16105174a28403eb207e40bfe76b3d364652f6cd55f171fa37a0f24aebce9257

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page