Skip to main content

A Django REST Framework-like package using Django Ninja

Project description

Ninja REST

A Django REST Framework-inspired package built on top of Django Ninja, providing familiar DRF-like features with the modern benefits of Django Ninja.

Features

  • Serializer-like Schema classes with field validation
  • ViewSet-like API controllers
  • Authentication mixins
  • Permission classes
  • Pagination support
  • Filtering and ordering
  • Nested relationship handling

Installation

pip install ninja_rest

Quick Start Guide

1. Basic Setup

First, add 'ninja_rest' to your INSTALLED_APPS:

# settings.py
INSTALLED_APPS = [
    ...
    'ninja_rest',
]

2. Define Your Models

# models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)

3. Create Schemas

# schemas.py
from ninja_rest import NinjaModelSchema
from django.contrib.auth.models import User
from .models import Post

class UserSchema(NinjaModelSchema):
    class Config:
        model = User
        fields = ['id', 'username', 'email']

class PostSchema(NinjaModelSchema):
    author: UserSchema

    class Config:
        model = Post
        fields = ['id', 'title', 'content', 'created_at', 'author']

4. Create ViewSets

# views.py
from ninja_rest import NinjaViewSet
from ninja_rest.permissions import IsAuthenticated
from ninja_rest.pagination import PageNumberPagination
from .schemas import PostSchema
from .models import Post

class PostViewSet(NinjaViewSet):
    schema = PostSchema
    queryset = Post.objects.select_related('author')
    pagination_class = PageNumberPagination
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # Custom queryset filtering
        if self.request.query_params.get('my_posts'):
            return self.queryset.filter(author=self.request.user)
        return self.queryset

5. Register URLs

# urls.py
from ninja import Router
from .views import PostViewSet

api = Router()

# This will create the following endpoints:
# GET /posts/ - List all posts
# POST /posts/ - Create a new post
# GET /posts/{id}/ - Retrieve a post
# PUT /posts/{id}/ - Update a post
# DELETE /posts/{id}/ - Delete a post
PostViewSet.register(api, 'posts')

Advanced Usage

Custom Authentication

from ninja_rest.authentication import TokenAuthentication

class CustomTokenAuth(TokenAuthentication):
    def authenticate(self, request, token):
        try:
            return CustomToken.objects.get(key=token).user
        except CustomToken.DoesNotExist:
            return None

class SecureViewSet(NinjaViewSet):
    authentication_classes = [CustomTokenAuth]

Custom Permissions

from ninja_rest.permissions import BasePermission

class IsOwner(BasePermission):
    def has_object_permission(self, request, obj):
        return obj.author == request.user

class PostViewSet(NinjaViewSet):
    permission_classes = [IsAuthenticated, IsOwner]

Custom Pagination

from ninja_rest.pagination import PageNumberPagination

class CustomPagination(PageNumberPagination):
    class Input(Schema):
        page: int = 1
        page_size: int = 50

class PostViewSet(NinjaViewSet):
    pagination_class = CustomPagination

Schema Validation

from ninja import Schema
from ninja_rest import NinjaModelSchema

class PostCreateSchema(NinjaModelSchema):
    title: str
    content: str

    class Config:
        model = Post
        fields = ['title', 'content']

    @validator('title')
    def title_must_be_capitalized(cls, v):
        if not v[0].isupper():
            raise ValueError('Title must be capitalized')
        return v

Testing

from django.test import TestCase
from ninja.testing import TestClient

class TestPostViewSet(TestCase):
    def setUp(self):
        self.client = TestClient()
        self.user = User.objects.create_user('testuser')

    def test_create_post(self):
        response = self.client.post(
            '/api/posts/',
            json={
                'title': 'Test Post',
                'content': 'Test Content'
            },
            headers={'Authorization': f'Bearer {token}'}
        )
        self.assertEqual(response.status_code, 201)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

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

ninja_rest-0.1.0.tar.gz (9.8 kB view details)

Uploaded Source

Built Distribution

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

ninja_rest-0.1.0-py3-none-any.whl (10.0 kB view details)

Uploaded Python 3

File details

Details for the file ninja_rest-0.1.0.tar.gz.

File metadata

  • Download URL: ninja_rest-0.1.0.tar.gz
  • Upload date:
  • Size: 9.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.7

File hashes

Hashes for ninja_rest-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a61a6a7b3feddc10fdaad8b1b1195127a19eb3a180b2a1e37c6102fa745224f2
MD5 b1d86bee9994e02e1d63635dbbdd3882
BLAKE2b-256 c057c35e3b9820d1c6b6a571c909a601a86432e473aaf5a1ee6ecf2eaad9e84e

See more details on using hashes here.

File details

Details for the file ninja_rest-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: ninja_rest-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 10.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.7

File hashes

Hashes for ninja_rest-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 adc35724ac8218639ebf9ce56f929ed82c96c1d2774318d59e48c8e23ab6db42
MD5 2a0e70b6f9c411a75c6d6dab0ee92c4f
BLAKE2b-256 cd6304c11900aeee437e5766a8ea51bde3be976ccf80f1e557d9eb80a3acdbb2

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