Lesson 19 / 25

Generating Clients and Server Stubs

Generate SDKs and server interfaces with OpenAPI Generator and understand the trade-offs.

Code from the contract

OpenAPI Generator (a community fork of Swagger Codegen) produces client SDKs in dozens of languages (TypeScript, Java, Kotlin, Python, Go, C#, Swift and more) and server stubs or interfaces for frameworks such as Spring, ASP.NET Core and others. Generated clients give consumers typed models and methods named after operationIds, and keep many client languages consistent with one contract. Generated server interfaces (for example Spring *Api interfaces with interfaceOnly=true) let you implement controllers against the contract, so compile errors reveal drift. Trade-offs: generated code reflects the quality of your document (vague schemas produce Object types), different generators vary in maturity, and customisation is done through configuration options or templates rather than editing output. Treat generated code as a build artefact: regenerate it in the build, do not hand-edit it, and pin the generator version. Lighter alternatives exist too, such as openapi-typescript for TypeScript types only, and several commercial SDK generators.

One contract, many SDKs

A generator turns the contract into typed clients for several languages and server interfaces.

A document icon feeding a gear, which emits several small code-file icons with different coloured tabs.
Figure 7.1 — Generating clients and server interfaces from one document.

Generating a TypeScript client and Spring server interfaces

Run as part of the build so generated code never drifts.

# TypeScript client using fetch
npx @openapitools/openapi-generator-cli generate \
  -i api/openapi.yaml \
  -g typescript-fetch \
  -o clients/ts \
  --additional-properties=supportsES6=true,npmName=@shop/orders-client

# Spring Boot server interfaces only (you implement them)
npx @openapitools/openapi-generator-cli generate \
  -i api/openapi.yaml \
  -g spring \
  -o build/generated/orders-api \
  --additional-properties=interfaceOnly=true,useSpringBoot3=true,useTags=true

# TypeScript types only (lightweight alternative)
npx openapi-typescript api/openapi.yaml -o src/api/schema.d.ts

Generated code is a mirror of your schemas

If generated clients are full of any or Object, the document is underspecified. Fix schemas, required lists and formats in the contract rather than patching generated output.

Quick check: Why should generated code not be edited by hand?

  • Edits are lost the next time code is regenerated from the contract
  • It is read-only on disk
  • Editing breaks the OpenAPI document
  • Generators encrypt the code
Answer

Edits are lost the next time code is regenerated from the contract — Generated code should be reproducible from the contract; customise via configuration or templates.