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
| Category | Key Requirement | Description |
|---|---|---|
| Naming | Unique operationId | The operationId is used as the function/method name. It must be unique across the entire document and remain constant to prevent breaking changes. |
| Data Types | Explicit Schemas | Define reusable models in the components/schemas section. Avoid inline objects to ensure consistent class generation. |
| Validation | Required Fields | Explicitly mark required properties. This determines whether the generated code uses optional types (e.g., ? in TypeScript or Optional in Java). |
| Versioning | Semantic Versioning | Use 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
enumvalues to allow the generator to create type-safe enumerations rather than generic strings. - Consistent Casing: Ensure the API property casing (e.g.,
camelCasevssnake_case) aligns with your project's coding standards.