API Client Generation
python manage.py gen turns your Django REST Framework API into typed clients: TypeScript (operations, React Query v5
hooks, Zod schemas, MSW mocks), Python, Go, Rust and Swift. The OpenAPI document is the contract; a client is never edited
by hand.
How a TypeScript client is made
Six steps, each with one owner:
- drf-spectacular renders one OpenAPI document from your URLconf, validated as with
spectacular --validate --fail-on-warn. A warning stops generation. - The Python generator resolves each target’s groups to OpenAPI tags and slices the document. It stamps the
slice with the django-cfg version and contract, and reads per-operation facts from it:
- a view that accepts no credentials (
security: [{}]) becomesauth: 'none'; - a view marked
extend_schema(extensions=SIGN_IN_STEP)becomesskipAuthRefresh: true; - a GET marked
@invalidated_by("topic")carries its realtime topics.
- a view that accepts no credentials (
- Orval 8.48 (pinned in the frontend workspace) writes the tree: operation functions, React Query v5 hooks and
query keys, Zod schemas, MSW handlers, and a banner on every file. The generator adds the mutator shim,
CFG, the realtime topic builders, and formats the tree with your frontend’s prettier config. - The type-check gate runs
tsc --noEmiton the tree as your app will see it. Only a tree that compiles replaces the old one. - The runtime
@djangocfg/apiis small and hand-written. It resolves the API origin (proxy, static build, direct), keeps one session store per page with cross-tab sync and a Web Locks refresh, honours the flags, and turns failures intoApiClientError. A schema miss is reported, not thrown. See Runtime. BaseApp(@djangocfg/layouts) provides the QueryClient with django-cfg’s defaults and refreshes every query whose view isinvalidated_bya topic, through the QueryCache. See State management.
A fact about one operation is generated. State, and logic that spans requests, stays in the runtime. Python, Go, Rust and Swift targets use their own generators (openapi-python-client, ogen, progenitor, swift-openapi-generator) on the same slices.
Quick Start
1. Configure the groups
# api/config.py
from django_cfg import DjangoConfig, OpenAPIClientConfig, OpenAPIGroupConfig
class CryptoConfig(DjangoConfig):
openapi_client: OpenAPIClientConfig = OpenAPIClientConfig(
enabled=True,
api_prefix="apix", # default: "apix"
groups=[
OpenAPIGroupConfig(
name="core",
apps=["users", "accounts", "api_keys"],
title="Core API",
description="User management and API keys",
),
OpenAPIGroupConfig(
name="trading",
apps=["wallets", "orders", "transactions"],
title="Trading API",
),
],
)2. Describe the targets
# generation.py (next to manage.py)
from pathlib import Path
from django_cfg.modules.django_generator import Config, OpenAPI, Target, Language, TargetType
FRONTEND = Path(__file__).parent.parent / "frontend"
config = Config(
openapi=OpenAPI(
targets=[
Target(
lang=Language.TYPESCRIPT,
type=TargetType.WEB,
path=FRONTEND / "apps" / "web" / "app" / "_lib" / "api" / "generated",
groups=["core", "trading"],
),
Target(
lang=Language.PYTHON,
type=TargetType.SDK,
path=Path("sdk/api_client"),
groups=["core"],
),
],
),
)TypeScript targets take a few more options: Target options.
3. Generate
python manage.py gen # all targets
python manage.py gen --ts # TypeScript only
python manage.py gen --groups core # one group
python manage.py gen --dry-run # plan onlySee CLI Usage for every flag.
4. Mount BaseApp and use the client
// app/[locale]/layout.tsx (a client component): BaseApp provides the QueryClient and the session.
<BaseApp project="crypto" auth={{ apiUrl: process.env.NEXT_PUBLIC_API_URL }}>
{children}
</BaseApp>import { cryptoCoinsList, useCryptoCoinsList } from '@/api/generated/endpoints/crypto/crypto';
// Server Component
export async function CoinCount() {
const coins = await cryptoCoinsList({ page: 1 });
return <div>{coins.count} coins</div>;
}
// Client Component
export function Coins() {
const { data } = useCryptoCoinsList({ page: 1 });
return <div>{data?.count ?? '…'} coins</div>;
}Every app that mounts BaseApp lists @tanstack/react-query as a dependency. More in
Generated clients.
OpenAPIClientConfig parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
enabled | bool | False | Enable API client generation |
groups | list[OpenAPIGroupConfig] | [] | Application groups (required when enabled) |
api_prefix | str | "apix" | URL prefix for API endpoints |
output_dir | str | "openapi" | Base folder for the rendered schemas |
generate_python | bool | True | Generate Python clients |
generate_typescript | bool | True | Generate TypeScript clients |
client_structure | "flat" | "namespaced" | "namespaced" | Python: client.posts_list() or client.posts.list() |
mirror_to_tmp | bool | True | Copy each generated tree to <project>/.tmp/generated/<name>/ |
max_workers | int | 1 | Parallel workers |
There is no option for SSE stream generators or an events bridge: streams live in dedicated adapters. See Migrating from the old client.
Inspecting the contract
add_django_cfg_urls(urlpatterns) adds, for each configured group:
/cfg/openapi/{group}/schema/: the OpenAPI document;/cfg/openapi/{group}/docs/: Swagger UI;/cfg/openapi/{group}/redoc/: ReDoc.
Set auth_required=True on a group to require authentication for all three. The API views’ own
permission_classes remain the authority for endpoint access. drf-spectacular is configured for generation
(COMPONENT_SPLIT_REQUEST, COMPONENT_SPLIT_PATCH, per-group title and version).
Rules of thumb
- Commit the generated code with the serializer or view change that caused it, so a review shows what the change does to the clients.
- Use groups to keep each slice small; a group is a selection boundary, not a separate package or session.
- Give every operation a stable
operationIdand an explicit tag. A collision stops generation. - Keep runtime concerns out of generated code. Import operations and models from the tree;
auth,djangoFetchand the error classes from@djangocfg/api. - Read Pitfalls before writing the first hook.
Next Steps
- Generated clients: operations, hooks, keys, Zod, mocks
- Runtime: API origin modes, session, errors
- Target options
- Groups and CLI Usage
- Migrating from the old client
- Troubleshooting