Generating OpenAPI Spec
Use thegetOpenApiSpec() method to generate an OpenAPI specification from your defined routes:
OpenAPI 3.1.0 Benefits
Semola generates OpenAPI 3.1.0 specifications, which provide several advantages over 3.0:- Full JSON Schema Compatibility: Uses standard JSON Schema Draft 2020-12, removing the need for OpenAPI-specific schema extensions
- Better Null Handling: Uses standard JSON Schema type unions instead of the custom
nullablekeyword - Modern Features: Support for tuple validation, conditional schemas (if/then/else), and
$refwith sibling keywords - Improved Type Safety: More precise
exclusiveMinimum/exclusiveMaximumas numbers rather than booleans
Configuration Options
Configure OpenAPI generation in the API constructor:Additional OpenAPI Options
You can provide additional OpenAPI configuration:Route Documentation
Enhance your OpenAPI spec with route-level documentation:Documentation Fields
summary: Short description of the endpoint (appears in API docs)description: Detailed description (supports Markdown)operationId: Unique identifier for the operation (used by code generators)tags: Array of tags for grouping endpoints in documentation
Schema Reuse
To optimize your OpenAPI specification and reduce redundancy, you can define reusable schemas using the.meta({ id: "SchemaName" }) method. Schemas with an ID are extracted to components.schemas and referenced using $ref instead of being inlined everywhere they’re used.
Benefits
- Smaller spec size: Schema defined once, referenced multiple times
- Better maintainability: Update schema in one place
- Improved readability: Cleaner OpenAPI specifications
- Backward compatible: Schemas without
.meta({ id })are inlined as before
With Zod
With Valibot
With ArkType
Schema Reuse Example
Generated Spec Structure
Parameter Handling
Inline Parameters
Note: Query parameters, headers, cookies, and path parameters are always inlined (OpenAPI requirement), regardless of whether they have an ID.Path Parameters
Path parameters are automatically extracted and included in the OpenAPI spec:Middleware Integration
Middlewares can contribute to the OpenAPI spec by defining request and response schemas:Using the Generated Spec
Serve with Swagger UI
Export to File
Best Practices
- Use
.meta({ id })for reusable schemas - Reduces spec size and improves maintainability - Add descriptive summaries and tags - Makes your API documentation more useful
- Define operationIds - Helps code generators create better client code
- Include examples in schemas - Use Zod’s
.describe()or Valibot’s metadata for better docs - Document error responses - Include all possible status codes with schemas
- Use consistent naming - Schema IDs should follow a naming convention (e.g., PascalCase)
- Version your API - Update the version number when making breaking changes