# API Overview

## Purpose
Describe the overall API surface, routing, authentication, pagination, throttling, and response format implemented in the backend.

## Code Locations (exact paths)
- Root routing: `backend/igny8_core/urls.py`
- Module routers:
  - Auth: `backend/igny8_core/auth/urls.py`
  - Account management: `backend/igny8_core/api/urls.py`
  - Planner: `backend/igny8_core/modules/planner/urls.py`
  - Writer: `backend/igny8_core/modules/writer/urls.py`
  - System: `backend/igny8_core/modules/system/urls.py`
  - Billing (full): `backend/igny8_core/business/billing/urls.py`
  - Billing admin: `backend/igny8_core/modules/billing/admin_urls.py`
  - Automation: `backend/igny8_core/business/automation/urls.py`
  - Linker: `backend/igny8_core/modules/linker/urls.py`
  - Optimizer: `backend/igny8_core/modules/optimizer/urls.py`
  - Publisher: `backend/igny8_core/modules/publisher/urls.py`
  - Integration: `backend/igny8_core/modules/integration/urls.py`
- DRF settings: `backend/igny8_core/settings.py` (REST_FRAMEWORK config)
- Base viewsets/responses: `backend/igny8_core/api/base.py`, `backend/igny8_core/api/response.py`

## High-Level Responsibilities
- Expose REST endpoints under `/api/v1/*` for auth, account/team, planner, writer, system, billing, automation, linker, optimizer, publisher, and integration.
- Enforce unified response format, tenant scoping, authentication (API key/JWT/session/basic), and scoped throttling.
- Provide OpenAPI schema and interactive docs at `/api/schema`, `/api/docs`, `/api/redoc`.

## Detailed Behavior
- Routing (root): `/api/v1/auth/`, `/api/v1/account/`, `/api/v1/planner/`, `/api/v1/writer/`, `/api/v1/system/`, `/api/v1/billing/`, `/api/v1/admin/` (billing admin), `/api/v1/automation/`, `/api/v1/linker/`, `/api/v1/optimizer/`, `/api/v1/publisher/`, `/api/v1/integration/`. Admin + CSV helpers mounted under `/admin/`.
- Auth stack (settings REST_FRAMEWORK):
  - `APIKeyAuthentication` (WordPress bridge, sets request.account/site when Bearer token is not JWT-like).
  - `JWTAuthentication` (Bearer JWT access tokens).
  - `CSRFExemptSessionAuthentication` (session without CSRF for API).
  - Basic auth fallback.
- Permissions default AllowAny in settings; individual viewsets specify stricter permissions (e.g., `IsAuthenticatedAndActive`, role checks).
- Tenancy: `AccountContextMiddleware` sets `request.account`; base viewsets (`AccountModelViewSet`, `SiteSectorModelViewSet`) auto-filter querysets by account/site/sector and set account on create.
- Pagination: `CustomPageNumberPagination` (page/ page_size; defaults in settings).
- Filtering/search/ordering: enabled globally via DRF filter backends; viewsets declare fields and search options.
- Throttling: `DebugScopedRateThrottle` with scope keys defined in settings for auth, planner, writer, billing, automation, etc.; bypassed when `IGNY8_DEBUG_THROTTLE` true.
- Responses: success/error helpers wrap payloads with `success`, `data`/`error`, optional `errors`, and `request_id`.
- OpenAPI: drf-spectacular configured with tags, schema routes; interactive docs at `/api/docs` (Swagger UI) and `/api/redoc`.

## Data Structures / Models Involved (no code)
- See module-specific docs; API layer uses serializers tied to planner/writer/billing/auth/etc. models.

## Execution Flow
- Request → middleware (request ID, account context, resource tracking) → DRF auth (API key/JWT/session) → viewset/action → serializer validation → model ops → unified response. Pagination/filtering/search applied where configured.

## Cross-Module Interactions
- Auth endpoints issue JWTs consumed by all other modules.
- Tenancy middleware/context is shared across all module viewsets.
- Billing credits enforced in content/automation flows via service calls, surfaced through billing endpoints.

## State Transitions
- Handled in module viewsets (e.g., task status changes, run statuses); API layer mediates CRUD and custom actions.

## Error Handling
- Custom exception handler (enabled by default) wraps errors in unified format.
- Viewsets return structured 400/401/403/404/500 responses; throttling returns standard DRF throttle responses.

## Tenancy Rules
- Account/site/sector scoping enforced by middleware + base viewsets; admin/developer/system roles may bypass filters at the viewset layer per role helpers.

## Billing Rules
- Credit checks occur in service calls (content generation, automation); billing endpoints report balances/usage/limits. Some endpoints return 402 on insufficient credits.

## Background Tasks / Schedulers
- Automation and some AI flows run via Celery; API endpoints trigger tasks (e.g., automation run_now, writer auto_generate_content).

## Key Design Considerations
- Consistent routing under `/api/v1/` with module-specific routers.
- Unified responses and throttling scopes to keep client behavior consistent.
- OpenAPI docs generated from viewset/serializer annotations for discoverability.

## How Developers Should Work With This Module
- Mount new modules under `/api/v1/<module>/` in `igny8_core/urls.py`.
- Inherit from base viewsets to get scoping/unified responses; declare permissions, filters, and throttles per viewset.
- Annotate endpoints with drf-spectacular for accurate schema; keep success/error responses consistent via helpers.
