drf-api
Skill1 starsChanged 5 months agoMITView on GitHub
Builds DRF 3.16 REST endpoints on Django 5.2 — ModelViewSet plus DefaultRouter, a light list serializer split from a detail serializer via get_serializer_class, pagination defaults, a custom export @action, and a drf-spectacular OpenAPI schema. Use when adding or reviewing a ViewSet, serializer, router, or endpoint, splitting list vs detail payloads, wiring pagination, adding a CSV/export action, or generating the OpenAPI schema. Not for tenant queryset scoping (see multi-tenancy), role gating (see rbac-permissions), or the frontend Zod contract (see drf-zod-contract).
In this repository49 other files it gives its agents.
- accessibilitySkill
- ai-evalsSkill
- ai-integrationSkill
- architecture-decisionsSkill
- audit-loggingSkill
- aws-servicesSkill
- browser-e2e-testingSkill
- celery-tasksSkill
- changelogSkill
- ci-cdSkill
- codebase-guideSkill
- code-reviewSkill
- commit-messageSkill
- cookie-auth-csrfSkill
- dashboard-data-designSkill
- db-concurrencySkill
- debugSkill
- dependency-auditSkill
- deploy-awsSkill
- design-systemSkill
- drf-zod-contractSkill
- frontend-perfSkill
- git-workflowSkill
- i18n-rtlSkill
- incident-responseSkill
- migrationsSkill
- money-decimalSkill
- multi-tenancySkill
- nextjs-moduleSkill
- observabilitySkill
- perf-reviewSkill
- production-readinessSkill
- product-ux-designSkill
- rbac-permissionsSkill
- react-querySkill
- security-reviewSkill
- skill-authoringSkill
- tailwind-shadcnSkill
- tenant-session-switchSkill
- threat-modelingSkill
- verifySkill
- version-checkSkill
- visual-ui-designSkill
- webhook-handlerSkill
- websockets-channelsSkill
- write-testsSkill
- zod-formsSkill
- zustand-stateSkill
- example-skillSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 84
No global DEFAULT_PAGINATION_CLASS means unbounded list responses — set it once.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
DRF API (viewsets, serializers, routers, schema)
When to use
Adding or reviewing a REST endpoint on this stack — a serializer, a ModelViewSet,
router wiring, pagination, an export action, or the OpenAPI schema. Tenant scoping and
RBAC are prerequisites here, not re-explained: your ViewSet subclasses the fail-closed
tenant mixin (multi-tenancy) and declares {resource}_{action} permissions
(rbac-permissions) before you add anything below.
Pattern
One ModelViewSet per resource, registered on a single DefaultRouter. Serve a light
list serializer (few columns, no nested joins) for list, and a fat detail
serializer for retrieve/create/update, chosen in get_serializer_class() by
self.action. Pagination is a global default. Side-jobs (export, bulk ops) are custom
@actions, not new endpoints. The schema is generated, never hand-written.
Steps / idioms
Split the serializers, pick one by self.action, register a single router, and inherit
the tenant + RBAC mixins. One consolidated example:
# serializers.py — thin list row vs. fat detail payload
class InvoiceListSerializer(serializers.ModelSerializer):
class Meta:
model = Invoice
fields = ["id", "number", "total", "status"] # cheap list row
class InvoiceDetailSerializer(serializers.ModelSerializer):
lines = InvoiceLineSerializer(many=True, read_only=True) # nested, costly
class Meta:
model = Invoice
fields = ["id", "number", "total", "status", "lines", "notes"]
# views.py — one ViewSet; serializer chosen by action, tenant + RBAC inherited
class InvoiceViewSet(TenantScopedViewSet): # scopes queryset fail-closed
queryset = Invoice.objects.all()
permission_classes = [InvoiceRBAC] # {resource}_{action} gate
def get_serializer_class(self):
return InvoiceListSerializer if self.action == "list" else InvoiceDetailSerializer
@action(detail=False, methods=["get"]) # -> /api/invoices/export/
def export(self, request):
rows = self.filter_queryset(self.get_queryset()) # stays tenant-scoped
resp = HttpResponse(content_type="text/csv")
csv.writer(resp).writerows(rows.values_list("number", "total"))
return resp
# urls.py — one router derives the URLConf and the browsable/OpenAPI schema
router = DefaultRouter()
router.register(r"invoices", InvoiceViewSet, basename="invoice")
urlpatterns = router.urlsSet a global pagination default so every list is bounded: in settings.py, give
REST_FRAMEWORK a DEFAULT_PAGINATION_CLASS of
rest_framework.pagination.PageNumberPagination, a PAGE_SIZE (e.g. 25), and a
DEFAULT_SCHEMA_CLASS of drf_spectacular.openapi.AutoSchema. Generate the OpenAPI
schema with python manage.py spectacular --file schema.yml, and annotate non-obvious
actions with @extend_schema so the generated types stay accurate — the frontend
consumes this schema (see drf-zod-contract).
Throttle every API so no client can hammer it unbounded: in REST_FRAMEWORK set
DEFAULT_THROTTLE_CLASSES (e.g. UserRateThrottle, AnonRateThrottle) and
DEFAULT_THROTTLE_RATES (e.g. {"user": "1000/day", "anon": "100/day"}), tuned to your
traffic. For a heavy @action, give it its own throttle_scope and a dedicated rate.
Adapt to your repo
Rename Invoice, InvoiceLine, and the entreprise tenant FK to your models. Confirm
TenantScopedViewSet and your RBAC permission class exist (they are separate skills).
Pick a pagination class that fits your UI — PageNumberPagination for page numbers,
CursorPagination for infinite scroll or large offsets. Set PAGE_SIZE to your default.
Gotchas
- A single fat serializer on
listis the classic N+1 — split list vs detail and addselect_related/prefetch_relatedon the detail queryset (seeperf-review). - Custom
@actions bypass nothing automatically: re-runget_queryset()/filter_querysetso they stay tenant-scoped, and gate them under RBAC. - No global
DEFAULT_PAGINATION_CLASSmeans unbounded list responses — set it once. - Stream large exports with
StreamingHttpResponse; a fullHttpResponsebuffers the whole CSV in memory. get_serializer_classkeys offself.action— a typo silently falls through to the detail serializer; assert the split in a test.Model.save(update_fields=[...])skipsclean()/ full validation — enforce business rules inperform_updateorserializer.validate, never by relying onModel.cleanfiring on save.- A serializer
source="get_x_display"only resolves when the model field declareschoices=; otherwise it silently breaks — use aSerializerMethodFieldinstead. - One
ScopedRateThrottlescope is a single shared bucket per user across every endpoint using it, so a heavy action (bulk export, PDF generation) can starve unrelated endpoints — give it its ownthrottle_scopeso the buckets don't collide.
See also
multi-tenancyrbac-permissionsdrf-zod-contractperf-review
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

