Skip to main content

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

Project description

FastAPI Ronin

logo

FastAPI Ronin

Build REST APIs with Django REST Framework patterns in FastAPI

PyPi Version Supported Python Versions License


Transform your FastAPI development with familiar Django REST Framework patterns.

FastAPI Ronin 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 ronin who master their craft with precision and expertise, FastAPI Ronin helps you build reliable, well-structured APIs with time-tested patterns and best practices.


Documentation: bubaley.github.io/fastapi-ronin


📦 Installation

Install FastAPI Ronin using UV:

uv add fastapi-ronin

🚀 Quick Example

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

# main.py - Complete FastAPI Ronin application
from datetime import datetime

from fastapi import APIRouter, FastAPI
from tortoise import fields
from tortoise.contrib.fastapi import register_tortoise
from tortoise.contrib.pydantic import PydanticModel
from tortoise.models import Model

from fastapi_ronin.decorators import action, schema, viewset
from fastapi_ronin.pagination import PageNumberPagination
from fastapi_ronin.viewsets import ModelViewSet
from fastapi_ronin.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)


# Schemas
@schema(model=Company)
class CompanyCreateSchema(PydanticModel):
    name: str
    full_name: str


@schema(model=Company)
class CompanyReadSchema(PydanticModel):
    id: int
    name: str
    full_name: str
    created_at: datetime
    updated_at: datetime


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


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

    pagination = PageNumberPagination
    list_wrapper = PaginatedResponseDataWrapper
    single_wrapper = ResponseDataWrapper

    # permission_classes = [IsAuthenticatedOrReadOnly]

    @action(methods=['GET'], detail=False)
    async def stats(self) -> dict[str, int]:
        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 Ronin is designed with these principles in mind:

  • Familiar: If you know Django REST Framework, you already know FastAPI Ronin
  • 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 Ronin 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 Ronin 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_ronin-0.5.0.tar.gz (540.4 kB view details)

Uploaded Source

Built Distribution

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

fastapi_ronin-0.5.0-py3-none-any.whl (29.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_ronin-0.5.0.tar.gz.

File metadata

  • Download URL: fastapi_ronin-0.5.0.tar.gz
  • Upload date:
  • Size: 540.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.27 {"installer":{"name":"uv","version":"0.9.27","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_ronin-0.5.0.tar.gz
Algorithm Hash digest
SHA256 e3a4fba7288a18a6919970227741d6a8a5eaec16d40e1dc33d0bc92020cf2dc6
MD5 c5a5762aee9e41f68ecfb7a054ad7627
BLAKE2b-256 080e241c802dba07a8ea7ac2513572f1286e3bf10d62a2891583d6ff77bea5be

See more details on using hashes here.

File details

Details for the file fastapi_ronin-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_ronin-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 29.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.27 {"installer":{"name":"uv","version":"0.9.27","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_ronin-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a92349daf0d7969567d9978f25f6ff8e5b3da886d3e4da2a47325d4c8e82eaf6
MD5 fc42ef5a9e2158b30e6f57fb82e29b46
BLAKE2b-256 3ebf55cd70f6c94b39cc8f44d6a193ec6e24838976d2fdc83a44aaa613ce81b8

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