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.
What this skill does
# 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
```bash
pip install django-ninja
```
```python
# 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)
```python
# 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 `Schema` for input, `ModelSchema` for output
- Type hints drive validation and docs
- Use `resolve_*` for computed fields
### Endpoints
```python
# 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
```python
# 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
```python
# 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
```python
# 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
```python
# config/settings/base.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework_simplejwt.authentication.JWTAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 20,
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}
```
### Serializers
```python
# apps/blog/api/serializers.py
from rest_framework import serializers
from apps.blog.models import Article
class ArticleListSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField()
class Meta:
model = Article
fields = ["id", "title", "slug", "author", "status", "created_at"]
class ArticleDetailSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField(read_only=True)
tag_ids = serializers.PrimaryKeyRelatedField(
queryset=Tag.objects.all(), many=True, write_only=True, source="tags"
)
class Meta:
model = Article
fields = ["id", "title", "slug", "body", "author", "tags", "tag_ids", "created_at"]
read_only_fields = ["slug", "created_at"]
```
### ViewSets
```python
# apps/blog/api/views.py
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.select_related("author").prefetch_related("tags")
lookup_field = "slug"
def get_serializer_class(self):
if self.action == "list":
return ArticleListSerializer
return ArticleDetailSerializer
def perform_create(self, serializer):
serializer.save(author=self.request.user)
@action(detail=True, methods=["post"])
def publish(self, request, slug=None):
article = self.get_object()
article.status = "published"
article.save(update_fields=["status"])
return Response({"status": "published"})
```
### Async DRF (via adrf)
```bash
pip install adrf
```
```python
from adrf.viewsets import ViewSet
from rest_framework.response import Response
class AsyncArticleViewSet(ViewSet):
async def list(self, request):
articles = await sync_to_async(list)(Article.objects.all()[:20])
serializer = ArticleListSerializer(articles, many=True)
return Response(serializer.data)
```
---
## Common Patterns (Both Frameworks)
### Filtering
```python
# Django Ninja
@router.get("/", response=list[ArticleOut])
def list_articles(
request,
status: str | None = None,
author: str | None = None,
created_after: date | None = None,
):
qs = Article.objects.all()
if status:
qs = qs.filter(status=status)
if author:
qs = qs.filter(author__username=author)
if created_after:
qs = qs.filter(created_at__date__gte=created_after)
return qs
```
```python
# DRF with django-filter
class ArticleFilter(djangRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.