django-api
БесплатноБез исполняемых скриптовНе проверенDjango API development for 2025. Covers Django Ninja (modern, async-first, type-safe) and Django REST Framework (mature, ecosystem-rich). Use when building…
от jpoutrin★ 16 звёзд на GitHubОб этом скилле
Django API Development (2025)
Framework Choice
| Factor | Django Ninja | Django REST Framework |
|---|---|---|
| Best for | New projects, performance-critical, type-safety | Complex apps, mature ecosystem needs |
| Validation | Pydantic (type hints) | Serializers |
| Async | Native, first-class | Via adrf package |
| Docs | Auto-generated OpenAPI | Via drf-spectacular |
| Learning curve | Lower (FastAPI-like) | Steeper but well-documented |
| Ecosystem | Growing | Extensive third-party packages |
Recommendation: Start with Django Ninja for new projects. Use DRF when you need its ecosystem (complex permissions, nested routers, etc).
Django Ninja (Recommended for 2025)
Setup
pip install django-ninja
# config/urls.py
from ninja import NinjaAPI
api = NinjaAPI(
title="My API",
version="1.0.0",
docs_url="/docs", # Swagger UI at /api/docs
)
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", api.urls),
]
Schemas (Pydantic)
# apps/blog/api/schemas.py
from ninja import Schema, ModelSchema
from datetime import datetime
from apps.blog.models import Article
class ArticleIn(Schema):
title: str
body: str
tag_ids: list[int] = []
class ArticleOut(ModelSchema):
author_name: str
class Meta:
model = Article
fields = ["id", "title", "slug", "status", "created_at"]
@staticmethod
def resolve_author_name(obj: Article) -> str:
return obj.author.username
class ArticleDetailOut(ArticleOut):
body: str
tags: list[str]
@staticmethod
def resolve_tags(obj: Article) -> list[str]:
return [t.name for t in obj.tags.all()]
Key patterns:
- Use
Schemafor input,ModelSchemafor output - Type hints drive validation and docs
- Use
resolve_*for computed fields
Endpoints
# apps/blog/api/views.py
from ninja import Router
from django.shortcuts import get_object_or_404
from apps.blog.models import Article
from .schemas import ArticleIn, ArticleOut, ArticleDetailOut
router = Router(tags=["articles"])
@router.get("/", response=list[ArticleOut])
def list_articles(request, status: str | None = None):
qs = Article.objects.select_related("author")
if status:
qs = qs.filter(status=status)
return qs
@router.get("/{slug}", response=ArticleDetailOut)
def get_article(request, slug: str):
return get_object_or_404(
Article.objects.select_related("author").prefetch_related("tags"),
slug=slug,
)
@router.post("/", response=ArticleOut)
def create_article(request, payload: ArticleIn):
article = Article.objects.create(
author=request.user,
title=payload.title,
body=payload.body,
)
if payload.tag_ids:
article.tags.set(payload.tag_ids)
return article
Async Endpoints
# apps/blog/api/views.py
from ninja import Router
from asgiref.sync import sync_to_async
router = Router()
@router.get("/articles/", response=list[ArticleOut])
async def list_articles(request):
# Wrap ORM calls with sync_to_async
qs = await sync_to_async(list)(
Article.objects.select_related("author")[:20]
)
return qs
@router.get("/external-data/")
async def fetch_external(request):
import httpx
async with httpx.AsyncClient() as client:
resp = await client.get("https://api.example.com/data")
return resp.json()
When to use async:
- External API calls (httpx, aiohttp)
- Multiple concurrent I/O operations
- Real-time / high-concurrency endpoints
Note: Django ORM is not fully async — wrap with sync_to_async.
Authentication
# apps/core/api/auth.py
from ninja.security import HttpBearer, APIKeyHeader
from django.contrib.auth.models import User
class AuthBearer(HttpBearer):
def authenticate(self, request, token: str) -> User | None:
# Validate JWT or token
try:
return User.objects.get(auth_token=token)
except User.DoesNotExist:
return None
class ApiKey(APIKeyHeader):
param_name = "X-API-Key"
def authenticate(self, request, key: str) -> User | None:
try:
return User.objects.get(api_key=key)
except User.DoesNotExist:
return None
# Usage
@router.get("/protected/", auth=AuthBearer())
def protected_endpoint(request):
return {"user": request.auth.username}
Wiring Routers
# config/urls.py
from ninja import NinjaAPI
from apps.blog.api.views import router as blog_router
from apps.users.api.views import router as users_router
api = NinjaAPI()
api.add_router("/articles", blog_router)
api.add_router("/users", users_router)
urlpatterns = [
path("api/v1/", api.urls),
]
Django REST Framework
Use when you need the mature ecosystem or complex features.
Setup
# config/settings/base.py
REST_FRAMEWORK
Установить django-api в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл django-api?
Django API development for 2025. Covers Django Ninja (modern, async-first, type-safe) and Django REST Framework (mature, ecosystem-rich). Use when building REST APIs, choosing between frameworks, implementing authentication, permissions, filtering, pagination, or async endpoints.
Как установить скилл django-api?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл django-api запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic