fastapi-mason


Namefastapi-mason JSON
Version 0.1.1 PyPI version JSON
download
home_pageNone
SummaryFastAPI Mason is a library for building FastAPI applications with a Django REST Framework-inspired architecture.
upload_time2025-07-12 00:20:21
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseMIT
keywords django django-rest-framework fastapi pagination tortoise viewsets
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FastAPI Mason

<p align="center">
  <img align="center" src="docs/assets/logo.png" alt="logo" width="200"/>
  <h2 align="center">FastAPI Mason</h2>
</p>
<p align="center" markdown=1>
  <i>Django REST Framework-inspired ViewSets and utilities for FastAPI applications with Tortoise ORM</i>
</p>
<p align="center" markdown=1>
<a href="https://pypi.org/project/fastapi-mason/">
  <img src="https://img.shields.io/pypi/v/fastapi-mason?color=%2334D058&label=pypi%20package" alt="PyPi Version"/>
</a>
<a href="https://pypi.org/project/fastapi-mason/">
  <img src="https://img.shields.io/pypi/pyversions/fastapi-mason.svg?color=%2334D058" alt="Supported Python Versions"/>
</a>
<a href="https://github.com/bubaley/fastapi-mason/blob/main/LICENSE">
  <img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License"/>
</a>
</p>

<hr>

**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.

<hr>
<p><b>Documentation</b>: <a class="link" href="https://bubaley.github.io/fastapi-mason">bubaley.github.io/fastapi-mason</a></p>
<hr>

<div style="margin: 2rem 0;">
  <a href="https://bubaley.github.io/fastapi-mason/quick-start/" class="get-started-btn">
    Get Started
  </a>
</div>

## 📦 Installation

Install FastAPI Mason using UV:

```bash
uv add fastapi-mason
```

## 🚀 Quick Example

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

```python
# 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:

```bash
uvicorn main:app --reload
```

 Try API Endpoints:

```json
"""
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):
{
  "data": 123
}
"""
```

## ✨ Key Features

<div class="feature-card">
  <h3>🎯 ViewSets</h3>
Django-like ViewSets with automatic CRUD operations and custom actions. Build complete REST APIs with minimal boilerplate code.
</div>

<div class="feature-card">
<h3>🔒 Permissions</h3>
Built-in permission system with customizable access control. Protect your endpoints with authentication and authorization rules.
</div>

<div class="feature-card">
<h3>📄 Pagination</h3>
Multiple pagination strategies out of the box: Limit/Offset and Page Number. You can easily customize or override pagination classes to suit your needs.
</div>

<div class="feature-card">
<h3>📋 Schema Generation</h3>
Intelligent schema generation with meta classes for fine-grained control over API serialization.
</div>

<div class="feature-card">
<h3>🔄 Response Wrappers</h3>
Consistent API response formatting with customizable wrapper classes.
</div>

<div class="feature-card">
<h3>⚡ State Management</h3>
Request-scoped state management for sharing data across middleware and view components.
</div>

## 🎯 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](https://bubaley.github.io/fastapi-mason/quick-start/) to get up and running in minutes.

Want to dive deeper? Explore our comprehensive guides:

- [ViewSets](https://bubaley.github.io/fastapi-mason/viewsets/) - Learn about the core ViewSet concepts
- [Schemas](https://bubaley.github.io/fastapi-mason/schemas/) - Master schema generation and meta classes
- [Permissions](https://bubaley.github.io/fastapi-mason/permissions/) - Secure your APIs with permission classes
- [Pagination](https://bubaley.github.io/fastapi-mason/pagination/) - Implement efficient data pagination
- [State Management](https://bubaley.github.io/fastapi-mason/state/) - Manage request-scoped state
- [Response Wrappers](https://bubaley.github.io/fastapi-mason/wrappers/) - Format consistent API responses

## 🤝 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.

- **GitHub**: [github.com/bubaley/fastapi-mason](https://github.com/bubaley/fastapi-mason)
- **Issues**: Report bugs and request features
- **Discussions**: Get help and share ideas

## 📄 License

FastAPI Mason is released under the [MIT License](https://github.com/bubaley/fastapi-mason/blob/main/LICENSE).

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fastapi-mason",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": "bubaley <bubaley.fu@gmail.com>",
    "keywords": "django, django-rest-framework, fastapi, pagination, tortoise, viewsets",
    "author": null,
    "author_email": "bubaley <bubaley.fu@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/e9/c8/56aa18b6efae230de85dca5d428c5f655ff24bae71c48f3fb697a32359c5/fastapi_mason-0.1.1.tar.gz",
    "platform": null,
    "description": "# FastAPI Mason\n\n<p align=\"center\">\n  <img align=\"center\" src=\"docs/assets/logo.png\" alt=\"logo\" width=\"200\"/>\n  <h2 align=\"center\">FastAPI Mason</h2>\n</p>\n<p align=\"center\" markdown=1>\n  <i>Django REST Framework-inspired ViewSets and utilities for FastAPI applications with Tortoise ORM</i>\n</p>\n<p align=\"center\" markdown=1>\n<a href=\"https://pypi.org/project/fastapi-mason/\">\n  <img src=\"https://img.shields.io/pypi/v/fastapi-mason?color=%2334D058&label=pypi%20package\" alt=\"PyPi Version\"/>\n</a>\n<a href=\"https://pypi.org/project/fastapi-mason/\">\n  <img src=\"https://img.shields.io/pypi/pyversions/fastapi-mason.svg?color=%2334D058\" alt=\"Supported Python Versions\"/>\n</a>\n<a href=\"https://github.com/bubaley/fastapi-mason/blob/main/LICENSE\">\n  <img src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" alt=\"License\"/>\n</a>\n</p>\n\n<hr>\n\n**Django REST Framework-inspired ViewSets and utilities for FastAPI applications with Tortoise ORM.**\n\nFastAPI 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.\n\nJust 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.\n\n<hr>\n<p><b>Documentation</b>: <a class=\"link\" href=\"https://bubaley.github.io/fastapi-mason\">bubaley.github.io/fastapi-mason</a></p>\n<hr>\n\n<div style=\"margin: 2rem 0;\">\n  <a href=\"https://bubaley.github.io/fastapi-mason/quick-start/\" class=\"get-started-btn\">\n    Get Started\n  </a>\n</div>\n\n## \ud83d\udce6 Installation\n\nInstall FastAPI Mason using UV:\n\n```bash\nuv add fastapi-mason\n```\n\n## \ud83d\ude80 Quick Example\n\nHere's a complete example showing how to build a REST API with FastAPI Mason:\n\n```python\n# main.py - Complete FastAPI Mason application\nfrom fastapi import APIRouter, FastAPI\nfrom tortoise import fields\nfrom tortoise.contrib.fastapi import register_tortoise\nfrom tortoise.models import Model\n\nfrom fastapi_mason.decorators import action, viewset\nfrom fastapi_mason.pagination import PageNumberPagination\nfrom fastapi_mason.schemas import SchemaMeta, generate_schema, rebuild_schema\nfrom fastapi_mason.viewsets import ModelViewSet\nfrom fastapi_mason.wrappers import PaginatedResponseDataWrapper, ResponseDataWrapper\n\n# Database setup\ndef register_database(app: FastAPI):\n    register_tortoise(\n        app,\n        db_url='sqlite://db.sqlite3',\n        modules={'models': ['main']},\n        generate_schemas=True,\n        add_exception_handlers=True,\n    )\n\n# Models\nclass Company(Model):\n    id = fields.IntField(primary_key=True)\n    name = fields.CharField(max_length=255)\n    full_name = fields.TextField(null=True)\n    created_at = fields.DatetimeField(auto_now_add=True)\n    updated_at = fields.DatetimeField(auto_now=True)\n\n# Schema meta\nclass CompanyMeta(SchemaMeta):\n    include = ('id', 'name', 'full_name', 'created_at', 'updated_at')\n\n# Schemas\nCompanySchema = generate_schema(Company, meta=CompanyMeta)\nCompanyCreateSchema = rebuild_schema(CompanySchema, exclude_readonly=True)\n\n# Views\nrouter = APIRouter(prefix='/companies', tags=['companies'])\n\n@viewset(router)\nclass CompanyViewSet(ModelViewSet[Company]):\n    model = Company\n    read_schema = CompanySchema\n    create_schema = CompanyCreateSchema\n\n    pagination = PageNumberPagination\n    list_wrapper = PaginatedResponseDataWrapper\n    single_wrapper = ResponseDataWrapper\n\n    # permission_classes = [IsAuthenticatedOrReadOnly]\n\n    @action(methods=['GET'], detail=False, response_model=dict[str, int])\n    async def stats(self):\n        return {'total': await Company.all().count()}\n\n# Application\napp = FastAPI(title='My API')\nregister_database(app)\napp.include_router(router)\n```\n\nStart server:\n\n```bash\nuvicorn main:app --reload\n```\n\n Try API Endpoints:\n\n```json\n\"\"\"\nThis creates the following endpoints:\n- GET /companies/ - List companies with pagination\n- POST /companies/ - Create new company  \n- GET /companies/{item_id}/ - Get specific company\n- PUT /companies/{item_id}/ - Update company\n- DELETE /companies/{item_id}/ - Delete company\n- GET /companies/stats/ - Custom stats endpoint\n\nExample API Responses:\n\nGET /companies/ (with pagination wrapper):\n{\n  \"data\": [\n    {\n      \"id\": 1,\n      \"name\": \"Acme Corp\",\n      \"full_name\": \"Acme Corporation Ltd.\",\n      \"created_at\": \"2023-01-01T10:00:00Z\",\n      \"updated_at\": \"2023-01-01T10:00:00Z\"\n    }\n  ],\n  \"pagination\": {\n    \"page\": 1,\n    \"page_size\": 10,\n    \"total_pages\": 5,\n    \"total_items\": 47\n  }\n}\n\nGET /companies/1/ (with single wrapper):\n{\n  \"data\": {\n    \"id\": 1,\n    \"name\": \"Acme Corp\", \n    \"full_name\": \"Acme Corporation Ltd.\",\n    \"created_at\": \"2023-01-01T10:00:00Z\",\n    \"updated_at\": \"2023-01-01T10:00:00Z\"\n  }\n}\n\nGET /companies/stats/ (custom action):\n{\n  \"data\": 123\n}\n\"\"\"\n```\n\n## \u2728 Key Features\n\n<div class=\"feature-card\">\n  <h3>\ud83c\udfaf ViewSets</h3>\nDjango-like ViewSets with automatic CRUD operations and custom actions. Build complete REST APIs with minimal boilerplate code.\n</div>\n\n<div class=\"feature-card\">\n<h3>\ud83d\udd12 Permissions</h3>\nBuilt-in permission system with customizable access control. Protect your endpoints with authentication and authorization rules.\n</div>\n\n<div class=\"feature-card\">\n<h3>\ud83d\udcc4 Pagination</h3>\nMultiple pagination strategies out of the box: Limit/Offset and Page Number. You can easily customize or override pagination classes to suit your needs.\n</div>\n\n<div class=\"feature-card\">\n<h3>\ud83d\udccb Schema Generation</h3>\nIntelligent schema generation with meta classes for fine-grained control over API serialization.\n</div>\n\n<div class=\"feature-card\">\n<h3>\ud83d\udd04 Response Wrappers</h3>\nConsistent API response formatting with customizable wrapper classes.\n</div>\n\n<div class=\"feature-card\">\n<h3>\u26a1 State Management</h3>\nRequest-scoped state management for sharing data across middleware and view components.\n</div>\n\n## \ud83c\udfaf Philosophy\n\nFastAPI Mason is designed with these principles in mind:\n\n- **Familiar**: If you know Django REST Framework, you already know FastAPI Mason\n- **Flexible**: Customize every aspect while maintaining sensible defaults\n- **Fast**: Built on FastAPI's high-performance foundation\n- **Modular**: Use only what you need, when you need it\n\n## \ud83d\udcda Getting Started\n\nReady to build amazing APIs? Start with our [Quick Start guide](https://bubaley.github.io/fastapi-mason/quick-start/) to get up and running in minutes.\n\nWant to dive deeper? Explore our comprehensive guides:\n\n- [ViewSets](https://bubaley.github.io/fastapi-mason/viewsets/) - Learn about the core ViewSet concepts\n- [Schemas](https://bubaley.github.io/fastapi-mason/schemas/) - Master schema generation and meta classes\n- [Permissions](https://bubaley.github.io/fastapi-mason/permissions/) - Secure your APIs with permission classes\n- [Pagination](https://bubaley.github.io/fastapi-mason/pagination/) - Implement efficient data pagination\n- [State Management](https://bubaley.github.io/fastapi-mason/state/) - Manage request-scoped state\n- [Response Wrappers](https://bubaley.github.io/fastapi-mason/wrappers/) - Format consistent API responses\n\n## \ud83e\udd1d Community\n\nFastAPI 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.\n\n- **GitHub**: [github.com/bubaley/fastapi-mason](https://github.com/bubaley/fastapi-mason)\n- **Issues**: Report bugs and request features\n- **Discussions**: Get help and share ideas\n\n## \ud83d\udcc4 License\n\nFastAPI Mason is released under the [MIT License](https://github.com/bubaley/fastapi-mason/blob/main/LICENSE).\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "FastAPI Mason is a library for building FastAPI applications with a Django REST Framework-inspired architecture.",
    "version": "0.1.1",
    "project_urls": {
        "Documentation": "https://github.com/bubaley/fastapi-mason#readme",
        "Homepage": "https://github.com/bubaley/fastapi-mason",
        "Repository": "https://github.com/bubaley/fastapi-mason.git"
    },
    "split_keywords": [
        "django",
        " django-rest-framework",
        " fastapi",
        " pagination",
        " tortoise",
        " viewsets"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "4b3160f5dc5bff8842fd33c3d705a2beaea074c46caacc5d31bc985e555d73f0",
                "md5": "39d47f3edfce499a1be787f226dbaea6",
                "sha256": "a53810cfceeac2051ef5ea67381104916440aa98cc357037b879dd08fcc798f7"
            },
            "downloads": -1,
            "filename": "fastapi_mason-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "39d47f3edfce499a1be787f226dbaea6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 20974,
            "upload_time": "2025-07-12T00:20:19",
            "upload_time_iso_8601": "2025-07-12T00:20:19.745129Z",
            "url": "https://files.pythonhosted.org/packages/4b/31/60f5dc5bff8842fd33c3d705a2beaea074c46caacc5d31bc985e555d73f0/fastapi_mason-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e9c856aa18b6efae230de85dca5d428c5f655ff24bae71c48f3fb697a32359c5",
                "md5": "a1f8f0bd5fc5bc9f94dabc78a19327ce",
                "sha256": "fd8891a6f24159dc2a983a5bc4e07576f0169e05b4935047e007e2986acf3364"
            },
            "downloads": -1,
            "filename": "fastapi_mason-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "a1f8f0bd5fc5bc9f94dabc78a19327ce",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 513285,
            "upload_time": "2025-07-12T00:20:21",
            "upload_time_iso_8601": "2025-07-12T00:20:21.339961Z",
            "url": "https://files.pythonhosted.org/packages/e9/c8/56aa18b6efae230de85dca5d428c5f655ff24bae71c48f3fb697a32359c5/fastapi_mason-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-12 00:20:21",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "bubaley",
    "github_project": "fastapi-mason#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-mason"
}
        
Elapsed time: 0.44129s