Skip to Content
FeaturesAPI GenerationGenerated Clients

Using Generated Clients

python manage.py gen writes one client per Target. This page shows how to use them. The TypeScript client is generated by Orval and runs on the small @djangocfg/api runtime; how that runtime resolves the API origin and keeps the session is on Runtime.

TypeScript Clients

This section describes the default web profile. For non-React command-line consumers, use the standalone CLI profile: generated Fetch operations and Zod models with an explicit per-call origin, without the frontend session runtime or hooks.

The tree

A TypeScript target is written into the path of its Target in generation.py. Point it at the folder your app imports from (for example app/_lib/api/generated); nothing is copied by hand. One target is one tree, whatever the number of groups:

generated/ endpoints/<tag>/<tag>.ts operations, React Query v5 hooks, query keys endpoints/<tag>/<tag>.msw.ts MSW handlers models/*.zod.ts Zod schemas and their TypeScript types runtime/orval-mutator.ts the mutator every operation calls (generated) runtime/cfg.ts CFG = { version, contract } runtime/realtime-query.ts only when a view is invalidated_by a topic realtime.ts typed realtime topic builders openapi.json the slice it was generated from

Each group selects OpenAPI tags. A tag becomes one module under endpoints/; models and the runtime are shared. A separate deployable client needs a separate Target. Every file starts with a banner that names the Orval version and the django-cfg contract. Do not edit the tree: fix the serializer or view and regenerate.

Operations and hooks

Every operation comes twice: a plain async function for imperative and server code, and a React Query hook for components.

import { cryptoCoinsList, useCryptoCoinsList } from '@api/generated/endpoints/crypto/crypto'; // Server Component, route handler, or any non-React code export async function firstPage() { return cryptoCoinsList({ page: 1 }); } // Client Component export function CoinList() { const { data, isPending, error } = useCryptoCoinsList({ page: 1 }, { query: { staleTime: 60_000 } }); if (isPending) return <div>Loading…</div>; if (error) return <div>{error.message}</div>; return ( <ul> {data.results.map((coin) => ( <li key={coin.id}> {coin.symbol}: {coin.name} </li> ))} </ul> ); }

A hook takes query (TanStack options) and request (options for the request itself, DjangoRequestInit). An operation takes the same request options as its last argument. error is typed ApiClientError; see Errors.

Hooks run in the QueryClient that BaseApp provides. Do not create one yourself, and do not pass a client as the hook’s last argument: that is a second cache, invisible to realtime refresh. See Pitfalls.

Query keys and invalidation

Each GET has a key factory, get<Op>QueryKey(params). Invalidate through it; never write a key by hand.

import { useQueryClient } from '@tanstack/react-query'; import { getCryptoCoinsListQueryKey, useCryptoCoinsCreate, } from '@api/generated/endpoints/crypto/crypto'; export function useAddCoin() { const queryClient = useQueryClient(); return useCryptoCoinsCreate({ mutation: { // A prefix key: every page and filter of the list. onSuccess: () => queryClient.invalidateQueries({ queryKey: getCryptoCoinsListQueryKey() }), }, }); }

get<Op>QueryOptions(params, options) returns the same options the hook uses, for prefetchQuery or ensureQueryData. An operation whose view is @invalidated_by a topic has a hook instead, use<Op>QueryOptions, because the realtime metadata is added by a generated query-options mutator. Call those inside a component.

The query key holds the path and the parameters, not the locale. After a locale switch, invalidate. See Pitfalls.

Request options and flags

The generator writes the facts the spec states about each operation into its call, and the runtime acts on them:

FlagSet by the generator whenRuntime effect
auth: 'none'security is [{}] or [], or absent in a document without a global securityno Authorization from the session, no refresh, a 401 never signs the user out
skipAuthRefresh: truethe view is marked extend_schema(extensions=SIGN_IN_STEP)no refresh before or after; a 401 is a wrong code or password, returned as an APIError
origin: 'direct'the operation’s tag is in the Target’s direct_origin_tagssent to the API host, never through the proxy or a static-build relative URL
validation: 'strict'never (you set it per call)a Zod miss rejects with the ZodError instead of being reported

A caller can set or override any of them for one call:

import { cfgAccountsProfileRetrieve, useCfgAccountsProfileRetrieve } from '@djangocfg/api'; export async function profileFromTheApiHost(signal: AbortSignal) { return cfgAccountsProfileRetrieve({ signal, origin: 'direct' }); } export function useStrictProfile() { return useCfgAccountsProfileRetrieve({ request: { validation: 'strict' } }); }

django-cfg marks its own sign-in views (password login, OTP request and verify, the OAuth callbacks, 2FA verify). A view of your own:

from drf_spectacular.utils import extend_schema from django_cfg.core.contract import SIGN_IN_STEP @extend_schema(request=MagicLinkSerializer, responses={200: TokenPairSerializer}, extensions=SIGN_IN_STEP) class MagicLinkVerifyView(APIView): ...

Zod and validation events

Operations hand their response schema to the runtime. A response that does not match it is reported, not thrown: the runtime dispatches a zod-validation-error window event, which BaseApp’s error tracking and devtools pick up, and returns the data as the server sent it. A new enum value on the server therefore does not take a page down. Pass validation: 'strict' where you would rather fail.

import { onValidationError } from '@djangocfg/api'; export function logSchemaDrift() { return onValidationError(({ operation, error }) => { console.warn(`${operation} does not match its schema`, error.issues); }); }

A 2xx answer that is not JSON where a schema is expected (an SPA fallback, a CDN error page) is an APIError, not a validation event.

Infinite queries

With the Target option infinite=True, every GET that takes a page (else cursor) query parameter also gets use<Op>Infinite and get<Op>InfiniteQueryOptions. Orval does not write initialPageParam or getNextPageParam; spread the runtime’s helper for the django-cfg envelope:

import { drfCursorParams, drfPageParams } from '@djangocfg/api'; const pings = useRealtimeDemoPingsListInfinite({ page_size: 20 }, { query: { ...drfPageParams } }); // pings.data?.pages: one envelope per fetch; pings.fetchNextPage() follows next_page. const comments = useCommentsListInfinite({ object_id }, { query: { ...drfCursorParams } }); // next_cursor, or the cursor of a DRF `next` URL.

An infinite key starts with 'infinite', so a mutation that changes the list invalidates get<Op>InfiniteQueryKey(params) as well as get<Op>QueryKey(params). See Target options.

Realtime refresh

A list or detail view marked @invalidated_by("orders:{order_id}") refreshes itself. Its generated query carries the concrete topic names in meta.realtimeTopics; while a component uses it, BaseApp keeps those topics subscribed and invalidates the query on each message or gap. No app code. See Realtime: frontend.

Mocks

endpoints/<tag>/<tag>.msw.ts holds MSW handlers built from the same schemas, with Faker data. @djangocfg/api/mocks re-exports the handlers for the cfg endpoints. Use them in tests and Storybook; do not hand-write a second REST mock contract, and do not edit a handler to fix a schema problem.

The stamp

runtime/cfg.ts exports CFG = { version, contract }: the django-cfg that generated the tree and the oldest one that serves its contract. python manage.py gen --check-stamp compares it with the installed django-cfg; gen --check also compares each committed openapi.json with the current schema.

Enum names

Each OpenAPI enum becomes a named Zod enum and type. A TextChoices class on a model is named after the class (OAuthProviderEnum). An enum that comes from a plain Enum or a hand-written ChoiceField is named after the field (ErrorEnum, StatusEnum), which collides as soon as two fields share the name and then gets a hash suffix that changes between runs. Pin such a name in SpectacularConfig.enum_name_overrides; the value is a dotted path to a TextChoices class or to a callable returning (value, label) pairs identical to the field’s choices (labels are part of the match):

SpectacularConfig( enum_name_overrides={ "PaymentErrorCodeEnum": "myapp.payments.codes.payment_error_choices", }, )

python manage.py suggest_enum_overrides prints a working dictionary for every hash-suffixed name. django-cfg pins its own: OAuthErrorCodeEnum (the error of the OAuth endpoints, since 2.3.367).

Python Clients

Installation

A Python target is written into the path of its Target in generation.py (the paths below stand for that directory).

Group Organization

The client is built by openapi-python-client: Pydantic models, one subclient per tag, async support.

Install Locally

pip install -e path/to/python/target # Or add to requirements.txt echo "-e path/to/python/target" >> requirements.txt

Publish to PyPI

Package and publish:

cd path/to/python/target python -m build python -m twine upload dist/*

Basic Usage

from trading import Client from trading.api.default import ( list_wallets, get_wallet, create_order ) from trading.models import OrderCreate # Initialize client client = Client(base_url="https://api.cryptoplatform.com") client = client.with_headers({ "Authorization": "Bearer access-token" }) # Synchronous API calls wallets = list_wallets.sync(client=client) print(f"Found {len(wallets.results)} wallets") wallet = get_wallet.sync(id="btc-wallet-123", client=client) print(f"Wallet: {wallet.currency} - {wallet.balance}") # Create order order_data = OrderCreate( symbol="BTC/USDT", side="buy", amount=0.1, price=45000 ) new_order = create_order.sync( client=client, json_body=order_data ) print(f"Created order: {new_order.id}")

Async Usage

import asyncio from trading import Client from trading.api.default import ( list_wallets, create_order ) async def main(): client = Client(base_url="https://api.cryptoplatform.com") client = client.with_headers({ "Authorization": "Bearer access-token" }) # Async API calls wallets = await list_wallets.asyncio(client=client) print(f"Found {len(wallets.results)} wallets") new_order = await create_order.asyncio( client=client, json_body={"symbol": "ETH/USDT", "side": "buy", "amount": 1} ) print(f"Created: {new_order.id}") # Run async code asyncio.run(main())

Authentication

# Bearer token client = client.with_headers({ "Authorization": f"Bearer {access_token}" }) # API key client = client.with_headers({ "X-API-Key": "your-api-key" }) # Custom headers client = client.with_headers({ "X-Custom-Header": "value", "X-Request-ID": "unique-id" })

Multiple Groups

# Import clients from different groups from core import Client as CoreClient from trading import Client as TradingClient from market import Client as MarketClient # Initialize clients with shared authentication base_url = "https://api.cryptoplatform.com" headers = {"Authorization": "Bearer access-token"} core = CoreClient(base_url=base_url).with_headers(headers) trading = TradingClient(base_url=base_url).with_headers(headers) market = MarketClient(base_url=base_url).with_headers(headers) # Use each client from core.api.default import list_users, get_user from trading.api.default import list_wallets, list_orders from market.api.default import get_prices users = list_users.sync(client=core) wallets = list_wallets.sync(client=trading) orders = list_orders.sync(client=trading, status="open") prices = get_prices.sync(client=market, symbols=["BTC", "ETH"])

Django Integration

# views.py from django.http import JsonResponse from trading import Client from trading.api.default import list_wallets def get_user_wallets(request): """Get wallets for current user""" # Create API client client = Client(base_url="https://api.cryptoplatform.com") client = client.with_headers({ "Authorization": f"Bearer {request.user.access_token}" }) # Fetch wallets try: wallets = list_wallets.sync( client=client, user_id=request.user.id ) return JsonResponse({ 'wallets': [wallet.dict() for wallet in wallets.results] }) except Exception as e: return JsonResponse({'error': str(e)}, status=500)

FastAPI Integration

from fastapi import FastAPI, Depends from trading import Client from trading.api.default import list_wallets, list_orders app = FastAPI() def get_api_client(): """Dependency to get API client""" client = Client(base_url="https://api.cryptoplatform.com") return client.with_headers({ "Authorization": "Bearer service-token" }) @app.get("/wallets") async def get_wallets(client: Client = Depends(get_api_client)): """Get all wallets""" wallets = await list_wallets.asyncio(client=client) return {"wallets": [wallet.dict() for wallet in wallets.results]} @app.get("/orders") async def get_orders(status: str = "open", client: Client = Depends(get_api_client)): """Get orders by status""" orders = await list_orders.asyncio(client=client, status=status) return {"orders": [order.dict() for order in orders.results]}

Error Handling

from httpx import HTTPStatusError try: order = create_order.sync( client=client, json_body={"symbol": "BTC/USDT", "side": "buy", "amount": 0.1} ) except HTTPStatusError as e: print(f"HTTP {e.response.status_code}: {e.response.text}") except Exception as e: print(f"Error: {e}")

Rust Clients

A Rust target is one Cargo crate generated by progenitor  (Oxide): serde models and an async reqwest client with one builder-style method per operation. Install the generator once:

cargo install cargo-progenitor --version 0.17.0 --locked

The version is pinned (PROGENITOR_VERSION in django-cfg): another one fails the target with the install line, since the generator is written against its limits and output layout.

progenitor formats with rustfmt’s nightly options; with no nightly toolchain installed, django-cfg runs the stable rustfmt without them. Set RUSTFMT to choose one yourself. The finished crate is then formatted the way cargo fmt formats it, with the crate’s edition, your rustfmt.toml and your rust-toolchain.toml, so cargo fmt --all after make gen changes nothing. Without rustfmt the crate is written unformatted, with a warning.

The crate

FileWhat
src/lib.rsprogenitor’s output: types (models), Client, builder (one request builder per operation)
src/django.rsDjangoClientBuilder: base URL, token, API key, timeout
src/multipart.rsmultipart/form-data operations, which progenitor does not take, as methods on Client
openapi.jsonthe slice it was generated from
workspace-dependencies.tomlwith rust_workspace=True: the entries for the root’s [workspace.dependencies]

HTTPS comes from one of three features: default-tls (reqwest’s rustls on aws-lc-rs), rustls-no-provider and native-tls. A standalone crate turns default-tls on. A workspace member (rust_workspace=True) turns nothing on, so enable one in the consumer. With rustls-no-provider, install a provider first, for example rustls::crypto::ring::default_provider().install_default(). The crate re-exports reqwest, so a multipart::Part or a header value needs no reqwest of your own.

Usage

[dependencies] djangocfg-api = { path = "../rust/djangocfg-api" } tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use djangocfg_api::{DjangoClientBuilder, Error}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let api = DjangoClientBuilder::new() .base_url("https://api.example.com") // or DJANGOCFG_API_BASE_URL .token(std::env::var("ACCESS_TOKEN")?) // Authorization: Bearer … .build()?; let profile = api.cfg_accounts_profile_retrieve().send().await?; println!("{}", profile.into_inner().email); match api.cfg_accounts_profile_retrieve().send().await { Err(Error::ErrorResponse(r)) if r.status() == 401 => println!("sign in again"), other => { other?; } } let avatar = djangocfg_api::reqwest::multipart::Part::bytes(std::fs::read("me.png")?).file_name("me.png"); api.cfg_accounts_profile_avatar_create(avatar).await?; Ok(()) }

Unused dependencies (for example regress when no field has a pattern) are listed under [package.metadata.cargo-machete]. A crate inside a Cargo workspace: rust_workspace.

A method’s builder takes the path and query parameters and the body (.body(...) or the body_map closure); .send() returns ResponseValue<T> (.status(), .headers(), .into_inner()). A new token means a new client: call build() again.

What the generator changes for progenitor

progenitor reads OpenAPI 3.0 and allows one success type and one error type per operation. django-cfg feeds it a copy of the slice with:

  • 3.1 forms lowered: type: [X, "null"] and a null branch become nullable, const an enum;
  • string unions merged: a blank-able choice is one enum with "", a blank-able URL one string;
  • error bodies with no serializer, or of different types in one operation, mapped to one type, ApiErrorBody (serde_json::Value);
  • multipart-only operations removed and written into src/multipart.rs.

Two different 2xx serializers on one operation stop generation, naming the operation.

Swift Clients (iOS/macOS)

Django-CFG generates Swift clients using Apple’s official swift-openapi-generator. This produces native Swift code with async/await support.

External Generator

Swift generation requires swift-openapi-generator to be installed:

brew install swift-openapi-generator

Installation

Generated Swift clients are written into the path of the Swift Target in generation.py.

Add to Xcode Project

  1. Copy the generated directory to your iOS project
  2. Add files to your target in Xcode
  3. Install OpenAPIRuntime via SPM:
// Package.swift or Xcode SPM dependencies: [ .package(url: "https://github.com/apple/swift-openapi-runtime", from: "1.0.0"), .package(url: "https://github.com/apple/swift-openapi-urlsession", from: "1.0.0"), ]

Basic Usage

import OpenAPIRuntime import OpenAPIURLSession import TradingAPI // Generated client // Initialize client let client = Client( serverURL: URL(string: "https://api.cryptoplatform.com")!, transport: URLSessionTransport() ) // List wallets (async/await) Task { do { let response = try await client.walletsList() switch response { case .ok(let okResponse): let wallets = try okResponse.body.json for wallet in wallets.results { print("\(wallet.currency): \(wallet.balance)") } case .undocumented(let statusCode, _): print("Unexpected status: \(statusCode)") } } catch { print("Error: \(error)") } }

Authentication

// Add Bearer token via middleware struct AuthMiddleware: ClientMiddleware { let token: String func intercept( _ request: HTTPRequest, body: HTTPBody?, baseURL: URL, operationID: String, next: (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?) ) async throws -> (HTTPResponse, HTTPBody?) { var modifiedRequest = request modifiedRequest.headerFields[.authorization] = "Bearer \(token)" return try await next(modifiedRequest, body, baseURL) } } // Use with client let client = Client( serverURL: URL(string: "https://api.cryptoplatform.com")!, transport: URLSessionTransport(), middlewares: [AuthMiddleware(token: accessToken)] )

SwiftUI Integration

import SwiftUI struct WalletListView: View { @State private var wallets: [Wallet] = [] @State private var isLoading = true @State private var error: Error? private let client = Client( serverURL: URL(string: "https://api.cryptoplatform.com")!, transport: URLSessionTransport() ) var body: some View { Group { if isLoading { ProgressView() } else if let error = error { Text("Error: \(error.localizedDescription)") } else { List(wallets, id: \.id) { wallet in HStack { Text(wallet.currency) Spacer() Text(wallet.balance) } } } } .task { await loadWallets() } } private func loadWallets() async { do { let response = try await client.walletsList() if case .ok(let okResponse) = response { wallets = try okResponse.body.json.results } isLoading = false } catch { self.error = error isLoading = false } } }

Error Handling

do { let response = try await client.ordersCreate( body: .json(.init( symbol: "BTC/USDT", side: .buy, amount: 0.1, price: 45000 )) ) switch response { case .ok(let okResponse): let order = try okResponse.body.json print("Order created: \(order.id)") case .badRequest(let errorResponse): let error = try errorResponse.body.json print("Validation error: \(error.detail)") case .unauthorized: print("Not authenticated") case .undocumented(let statusCode, _): print("Unexpected status: \(statusCode)") } } catch { print("Network error: \(error)") }

Features

  • ✅ Native Swift types - Structs, enums, optionals
  • ✅ Async/await - Modern concurrency support
  • ✅ Type-safe responses - Exhaustive switch on response types
  • ✅ Middleware support - Authentication, logging, retry
  • ✅ Combine compatible - Works with publishers
  • ✅ SwiftUI ready - Use with @State, @StateObject

Type Safety

TypeScript Types

Request and response types come from the same Zod schemas. Import a model from models/:

import { cryptoCoinsList } from '@api/generated/endpoints/crypto/crypto'; import type { CoinListing } from '@api/generated/models/coinListing.zod'; export async function firstCoin(): Promise<CoinListing | undefined> { const coins = await cryptoCoinsList({ page: 1 }); return coins.results[0]; }

The types describe the contract. A response that misses its schema is still returned (and reported), so code that must not trust a field checks it, or calls with validation: 'strict'.

Python Types

Generated Python clients use attrs classes for type safety:

from cfg_support.models import Ticket, TicketCreate # Type hints work in IDEs def process_ticket(ticket: Ticket) -> None: print(ticket.id) # ✓ Valid print(ticket.title) # ✓ Valid print(ticket.invalid) # ❌ IDE error # Pydantic-style validation new_ticket = TicketCreate( title="Test", description="Test ticket", priority="high" ) # Invalid data raises validation error invalid = TicketCreate(priority="invalid") # ❌ ValidationError

Best Practices

  • One runtime boundary. Import operations, hooks and models from the generated tree; import auth, djangoFetch, APIError and friends from @djangocfg/api. No per-group client, token store, refresh handler or fetch wrapper.
  • One QueryClient, BaseApp’s. Use useQueryClient() to invalidate; use get<Op>QueryKey for keys.
  • Mocks next to the contract. Generated MSW handlers in tests and Storybook.
  • Retries belong to the QueryClient. BaseApp’s default retries a network error or a 5xx up to twice and never a 4xx. Change it on the client you pass as queryClient, not per call site.

Next Steps

Regenerate after API changes

After changing a serializer or view, regenerate and commit the tree with the change:

python manage.py gen
Last updated on