Django Ninjaのロゴ

Django Ninja

組織
CodeAtCode
django-ninja

Use when building Django REST APIs with django-ninja - Pydantic schemas, routers, CRUD endpoints, authentication, pagination, file uploads, async views, OpenAPI docs, or migrating from DRF

概要

公開者CodeAtCode
リポジトリoss-ai-skills
スキル名django-ninja
スター
30
フォーク
3
同梱ファイル
8
ライセンスGPL-3.0
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 8個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    CodeAtCodeがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキルDjango NinjaをTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/django-ninja
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/CodeAtCode/oss-ai-skills.git /tmp/oss-ai-skills
mkdir -p .claude/skills
cp -r /tmp/oss-ai-skills/frameworks/django-ninja .claude/skills/django-ninja
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでDjango Ninjaを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあると、モデルが自動的にDjango Ninjaを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Django Ninjaは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、未使用のスキルにはコストがかかりません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Objective: Use this skill to reduce schema-validation bypass, N+1-in-serializer incidents, auth-decorator misapplication, and OpenAPI-drift bugs by enforcing Pydantic-boundary discipline, queryset-loading rules, and router-auth patterns below.

Django Ninja

Build fast, type-safe REST APIs with Django and Pydantic v2.

Overview

Django Ninja provides automatic request validation, response serialization, and generates OpenAPI documentation.

Versions: django-ninja 1.6.x + Django 6.0 compatible. Requires Pydantic v2.

Installation

bash
pip install django-ninja

Django Integration

Do add ninja to INSTALLED_APPS because the framework needs its middleware and URL helpers:

python
# settings.py
INSTALLED_APPS = [
    # ...
    'ninja',
]

Basic Setup

Do create a NinjaAPI instance and expose it via Django URLs:

python
# api.py
from ninja import NinjaAPI

api = NinjaAPI()

@api.get("/hello")
def hello(request):
    return {"message": "Hello World"}

# urls.py
from django.urls import path
from .api import api

urlpatterns = [
    path("api/", api.urls),
]

Deep Dives

See these reference files for detailed patterns:

  • references/drf-migration.md — DRF-to-django-ninja migration patterns
  • references/schema-reference.md — Pydantic schema definitions, ModelSchema configuration, nested schemas
  • references/router-endpoints.md — HTTP methods, path/query parameters, request body, form data
  • references/auth-pagination-errors.md — Authentication methods, pagination strategies, error handling
  • references/crud-patterns.md — CRUD operations, bulk operations, relationship handling
  • references/files-async-openapi.md — File uploads, async support, OpenAPI customization
  • references/django-integration.md — Django ORM integration, middleware, signals, production practices
  • references/testing-troubleshooting.md — Testing with pytest, auth testing, common issues

Runtime Behavior

Validation Timing

Do rely on validation happening before the resolver executes because failed input never reaches your business logic:

python
# This never runs if payload fails validation
@api.post("/posts", response=PostSchema)
def create_post(request, payload: PostCreateSchema):
    # payload is guaranteed valid here
    return Post.objects.create(**payload.dict())

The response= Parameter

Do always specify response= because it affects both runtime serialization AND OpenAPI schema generation:

python
# Without response= — OpenAPI shows 200 with empty schema
@api.get("/health")
def health(request):
    return {"status": "ok"}  # Works, but docs are incomplete

# With response= — OpenAPI documents the actual response
@api.get("/health", response=dict)
def health(request):
    return {"status": "ok"}  # Docs show {"status": "string"}

Failure mode: omitting response= on endpoints that return data causes generated clients to have no type information.

dict/list Annotations Bypass Validation

Do use Schema classes instead of bare dict/list because raw types bypass Pydantic validation:

python
# Bypasses Pydantic validation — raw dict passthrough
@api.post("/raw", response=dict)
def raw_handler(request, payload: dict):
    return payload  # No validation, no type safety

# Use Schema for validation
@api.post("/typed", response=PostSchema)
def typed_handler(request, payload: PostCreateSchema):
    return Post.objects.create(**payload.dict())  # Validated

operation_id Contract

Do set stable operation_id values because code generation tools use them and changing them breaks existing clients:

python
# Stable operation IDs for client generation
@api.get("/posts/{id}", operation_id="get_post")
def get_post(request, id: int):
    ...

# Bad: changing this breaks existing generated clients
@api.get("/posts/{id}", operation_id="fetch_post")  # Breaking change!

Testing

TestClient from django-ninja

Do use TestClient for unit testing because it doesn't require a running server:

python
from ninja.testing import TestClient
from .api import api  # Your NinjaAPI instance

client = TestClient(api)

def test_list_posts():
    response = client.get("/posts")
    assert response.status_code == 200
    data = response.json()
    assert len(data) == 2
    assert data[0]["title"] == "Test Post"

def test_create_post():
    payload = {"title": "New Post", "body": "Content here"}
    response = client.post("/posts", json=payload)
    assert response.status_code == 200
    assert response.json()["id"] == 1

def test_validation_error():
    payload = {"title": ""}  # Missing required field
    response = client.post("/posts", json=payload)
    assert response.status_code == 422  # Validation error

Testing Auth Callbacks

Do test auth callbacks directly because they can fail independently of endpoints:

python
from ninja.security import HttpBearer

class CustomAuth(HttpBearer):
    def __call__(self, request, token: str):
        if not is_valid_token(token):
            raise PermissionError("Invalid token")
        request.user = get_user_by_token(token)
        return request.user

# Test the auth callback directly
def test_custom_auth_invalid():
    auth = CustomAuth()
    try:
        auth(None, "invalid_token")
        assert False, "Should have raised"
    except PermissionError:
        pass  # Expected

# Test endpoint with auth
@api.get("/protected", auth=CustomAuth())
def protected(request):
    return {"user": request.user.username}

def test_protected_endpoint():
    response = client.get("/protected")
    assert response.status_code == 401  # No auth header
    
    response = client.get("/protected", headers={"Authorization": "Bearer valid_token"})
    assert response.status_code == 200

Separating Resolver Logic from HTTP

Do extract business logic into pure functions because it makes testing easier without Django:

python
# business_logic.py — pure functions, no HTTP dependencies
def create_post_data(title: str, body: str, author_id: int) -> dict:
    """Pure function — easy to test without Django."""
    return {
        "title": title.strip(),
        "body": body.strip(),
        "author_id": author_id,
    }

# api.py — thin HTTP layer
class PostCreateSchema(Schema):
    title: str
    body: str

@api.post("/posts", response=PostSchema)
def create_post(request, payload: PostCreateSchema):
    data = create_post_data(payload.title, payload.body, request.user.id)
    return Post.objects.create(**data)

Ecosystem Libraries

django-ninja-extra

PyPI: django-ninja-extra | URL: https://github.com/eadwinCode/django-ninja-extra

Use when you need class-based controllers (@api_controller) or DRF-style permission classes. Tradeoff: adds complexity; prefer function-based handlers for simple APIs.

django-ninja-jwt

PyPI: django-ninja-jwt | URL: https://github.com/eadwinCode/django-ninja-jwt

Use for JWT authentication (obtain/refresh/verify tokens). Tradeoff: pulls in django-ninja-extra as a dependency. For custom token logic, write your own HttpBearer subclass instead.

django-ninja-aio-crud

PyPI: django-ninja-aio-crud | URL: https://github.com/caspel26/django-ninja-aio-crud

Use for auto-generated async CRUD endpoints with built-in filtering/pagination. Tradeoff: opinionated structure; harder to customize than hand-written handlers.

django-contract-tester

PyPI: django-contract-tester | URL: https://github.com/maticardenas/django-contract-tester

Use to validate test requests/responses against OpenAPI schemas. Tradeoff: only needed for strict contract testing; regular pytest assertions work for most cases.

References

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Django Ninja」では何ができますか?

Use when building Django REST APIs with django-ninja - Pydantic schemas, routers, CRUD endpoints, authentication, pagination, file uploads, async views, OpenAPI docs, or migrating from DRF

TypingMindでDjango Ninjaを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Django Ninjaはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにDjango Ninjaをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/django-ninjaを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Django Ninjaを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストが合致したときにこのスキルを読み込めます。

Django Ninjaは何個のAIモデルで使えますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもDjango Ninjaを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Django Ninja」は無料ですか?

はい。CodeAtCodeがGitHubでGPL-3.0ライセンスの下で公開しています。支払いが必要なのは、利用したトークンに対する、ご自身が契約するAIプロバイダーへの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇