Skip to content

Best Practices for Code Generation via OpenAPI

Using OpenAPI (Swagger) to automate API client generation significantly improves development efficiency. To ensure the generated code is stable and readable, please adhere to the following guidelines.

Core Considerations

CategoryKey RequirementDescription
NamingUnique operationIdThe operationId is used as the function/method name. It must be unique across the entire document and remain constant to prevent breaking changes.
Data TypesExplicit SchemasDefine reusable models in the components/schemas section. Avoid inline objects to ensure consistent class generation.
ValidationRequired FieldsExplicitly mark required properties. This determines whether the generated code uses optional types (e.g., ? in TypeScript or Optional in Java).
VersioningSemantic VersioningUse the info.version field. Breaking changes in the API should trigger a major version bump in the generated SDK.

Important Notes

  • Avoid Overlapping Tags: Generators often group files by tags. Keep tag names clean and organized.
  • Enums: Clearly define enum values to allow the generator to create type-safe enumerations rather than generic strings.
  • Consistent Casing: Ensure the API property casing (e.g., camelCase vs snake_case) aligns with your project's coding standards.