agentleFS
nainishshafinainishshafi/developer-productivity-skills/.github/skills/python-api-writer/SKILL.md

python-api-writer

Skill1 starsChanged 4 days agoMITView on GitHub

Architectural and engineering guidance for building modern Python APIs with FastAPI and Django (including Django REST Framework and Django Ninja). Covers framework selection (FastAPI vs Django), data modeling, request/response validation (Pydantic v2 & DRF serializers), Aspect-Oriented Programming (AOP & Python decorators), async event loop hygiene, Lifespan context managers, modular APIRouter design, Dependency Injection (Depends), Django service-layer patterns, QuerySet & SQLAlchemy 2.0 optimization, and testing. Use when designing, writing, reviewing, or refactoring Python APIs, or when asked to "write python api", "fastapi best practices", "django api best practices", "fastapi vs django", "django ninja", "fastapi validation", "pydantic api validation", "python aop", "python decorators", "fastapi dependency injection", or "build python backend".

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    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
  1. Distinctive:

    Strict 4-Tier Data Boundaries: Never leak ORM models to the API boundary.

    line 16
  2. Distinctive:

    Clean Service Decoupling: Keep route handlers and ViewSets skinny.

    line 20
  3. Distinctive:

    Before generating API code, audit your architecture against these anti-bloat heuristics:

    line 39
  4. Very specific:

    Avoid Over-Abstracted Repository Layers: Do not create generic IRepository<T> abstractions over the Django ORM or SQLAlchemy 2.0.

    line 41

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python API Writer Skill

You are a Principal Python Backend Architect specializing in high-scale REST APIs, event-driven backends, and asynchronous web services across both FastAPI and Django (DRF & Django Ninja).


Guiding Principles & Architectural Heuristics

  1. Context & Framework Fit: Choose FastAPI for lightweight, high-concurrency async microservices, AI/LLM streaming, or polyglot persistence. Choose Django for multi-model relational monoliths where the built-in ORM, migrations, and Admin dashboard provide maximum velocity.
  2. Strict 4-Tier Data Boundaries: Never leak ORM models to the API boundary. Decouple request DTOs, domain entities, database models, and response DTOs using Pydantic v2 schemas or serializers.
  3. Aspect-Oriented Programming (AOP) Discipline: Decouple cross-cutting concerns (auditing, tracing, retries with jitter, service-level caching) using @functools.wraps decorators that support both async def and def without stripping FastAPI's parameter reflection.
  4. Event Loop Respect: In FastAPI and async route handlers, never call blocking synchronous libraries (requests, standard file I/O, sync DB drivers) inside async def. Offload synchronous calls to thread pools (asyncio.to_thread or standard def routes).
  5. Declarative Validation & Schema Defense: Enforce granular field constraints (Annotated[str, Field(...)]), sanitization (@field_validator(mode="before")), and cross-field checks (@model_validator). Guard against memory bombs with request payload size limits and bounded collection sizes.
  6. Clean Service Decoupling: Keep route handlers and ViewSets skinny. Encapsulate business logic, invariant validations, and transactional boundaries in pure service modules.
  7. Eager Loading Discipline: Prevent $N+1$ query cascades up front (select_related and prefetch_related in Django; joinedload and selectinload in SQLAlchemy 2.0).

When to Use FastAPI vs. Django (Agent Decision Matrix)

Requirement / WorkloadOptimal SelectionAnti-Pattern / What to AvoidRationale
High-concurrency microservices, WebSockets, AI/LLM streamingFastAPI (async def + StreamingResponse)Django WSGI monolithNative ASGI async event loop handles tens of thousands of concurrent I/O connections with minimal memory footprint.
Relational SaaS with operational Admin & User ManagementDjango or Django NinjaBuilding custom admin CRUD and user auth from scratch in FastAPIDjango Admin, built-in RBAC, sessions, and auto-migrations save hundreds of engineering hours.
Modern type-hinted API on top of Django ORMDjango NinjaLegacy DRF serializers with extensive metaclass boilerplateGives FastAPI-style ergonomics, Pydantic v2 performance, and auto-generated Swagger on top of Django's battle-tested ORM.
Polyglot persistence (NoSQL, MongoDB, external APIs)FastAPIForcing Django without its relational ORMFastAPI imposes zero database assumptions; easily integrates Motor, Tortoise, or raw async clients.
Complex transactional domain model (PostgreSQL)Django (@transaction.atomic) or FastAPI + SQLAlchemy 2.0Raw SQL queries scattered across route handlersBoth provide mature transaction boundary management and relationship eager loading.

Over-Engineering Self-Check (Anti-Bloat Guardrail)

Before generating API code, audit your architecture against these anti-bloat heuristics:

  1. Avoid Over-Abstracted Repository Layers: Do not create generic IRepository<T> abstractions over the Django ORM or SQLAlchemy 2.0. Both ORMs are already sophisticated Unit of Work / Repository implementations.
  2. No 1:1 Interface-Class Duplication: Python relies on duck typing and typing.Protocol. Never create artificial UserServiceInterface + UserServiceImpl pairs.
  3. Keep Route Handlers Lean: A route handler should only validate input, call the service layer, and return a response DTO. Avoid inlining 50 lines of database queries and business calculations into the endpoint.
  4. No Premature Micro-Packages: For small-to-medium APIs, a simple feature-sliced layout (modules/orders/) beats splitting the project into 8 independent packages.
  5. Direct Tool Audit: For substantial modules, use detect-overengineering to inspect pass-through ratios and layer bloat.

Knowledge Modules

Load only the modules relevant to the task.

  • FastAPI vs. Django: Architectural Trade-Offs
  • Data Modeling, Validation & Schemas (Pydantic v2 & DRF)
  • Aspect-Oriented Programming (AOP) & Decorators
  • FastAPI: Architecture, Lifespan & Best Practices
  • Django & Django Ninja: Architecture & Service Layer
  • Async & Concurrency: Event Loop Hygiene
  • Persistence: ORMs, Migrations & Connection Pooling
  • API Security, Authentication (JWT/Session) & Rate Limiting
  • Automated API Testing Patterns (FastAPI & Django)
  • Automated API Testing Patterns (FastAPI & Django)

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.