### Complete Elysia OpenAPI Plugin Setup Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Provides a comprehensive example of setting up the Elysia OpenAPI plugin, including type imports, Zod integration, and basic route definition. ```typescript // Basic setup import { Elysia, t } from 'elysia' import { openapi, fromTypes } from '@elysia/openapi' import * as z from 'zod' // Type imports import type { ElysiaOpenAPIConfig, OpenAPIProvider, AdditionalReference } from '@elysia/openapi' import type { OpenAPIGeneratorOptions } from '@elysia/openapi/gen' import type { SwaggerUIOptions } from '@elysia/openapi/swagger/types' // Internal function imports (for advanced use) import { toOpenAPISchema, withHeaders, getPossiblePath, enumToOpenApi, unwrapSchema } from '@elysia/openapi' // UI renderers (for custom implementations) import { SwaggerUIRender } from '@elysia/openapi/swagger' import { ScalarRender } from '@elysia/openapi/scalar' // Complete plugin setup const app = new Elysia() .use( openapi({ documentation: { info: { title: 'My API', version: '1.0.0' } }, references: fromTypes(), mapJsonSchema: { zod: z.toJSONSchema } }) ) .post('/users', ({ body }) => body, { body: z.object({ name: z.string() }) }) .listen(3000) ``` -------------------------------- ### Install Elysia OpenAPI Plugin Source: https://github.com/elysiajs/elysia-openapi/blob/main/README.md Install the @elysia/openapi package using bun. ```bash bun add @elysia/openapi ``` -------------------------------- ### Basic Elysia App with OpenAPI Documentation Source: https://github.com/elysiajs/elysia-openapi/blob/main/README.md An example of an Elysia application using the openapi plugin to document GET and POST routes with defined schemas. Access the documentation at http://localhost:3000/openapi. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' const app = new Elysia() .use(openapi()) .get('/', () => 'hi', { response: t.String({ description: 'sample description' }) }) .post( '/json/:id', ({ body, params: { id }, query: { name } }) => ({ ...body, id, name }), { params: t.Object({ id: t.String() }), query: t.Object({ name: t.String() }), body: t.Object({ username: t.String(), password: t.String() }), response: t.Object( { username: t.String(), password: t.String(), id: t.String(), name: t.String() }, { description: 'sample description' } ) } ) .listen(3000) ``` -------------------------------- ### Basic Header Validation Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/withHeaders.md Demonstrates how to use `withHeaders` to add a simple `authorization` header to a response schema for a GET request. ```APIDOC ## GET /api/data ### Description Retrieves data with basic header validation. ### Method GET ### Endpoint /api/data ### Parameters #### Request Body (Not applicable for this example) #### Response ##### Success Response (200) - **data** (string) - The data payload. ##### Headers - **authorization** (string) - Bearer token. ### Request Example (Not applicable for this example) ### Response Example ```json { "data": "value" } ``` ``` -------------------------------- ### Complete Elysia OpenAPI Configuration Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/configuration.md Demonstrates a comprehensive configuration for the Elysia OpenAPI plugin, including API information, server details, exclusion rules, schema mapping, references, and Scalar UI settings. This example shows how to integrate Zod for schema validation and define API endpoints with their responses. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' import * as z from 'zod' new Elysia() .use( openapi({ enabled: true, path: '/api/docs', provider: 'scalar', specPath: '/api/spec.json', embedSpec: false, documentation: { info: { title: 'My API', description: 'Complete API', version: '1.0.0' }, servers: [ { url: 'https://api.example.com', description: 'Production' } ] }, exclude: { methods: ['options'], paths: ['/health', /^\/internal/], staticFile: true, tags: ['internal'] }, mapJsonSchema: { zod: z.toJSONSchema }, references: () => ({ '/users': { get: { params: t.Never(), query: t.Object({ limit: t.Optional(t.Number()) }), headers: t.Never(), body: t.Never(), response: { 200: t.Array(t.Object({ id: t.Number() })) } } } }), scalar: { version: '1.13.10', theme: 'kepler', darkMode: true } }) ) .get('/users', () => []) .listen(3000) ``` -------------------------------- ### Elysia Quick Start with @elysia/openapi Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/README.md This snippet demonstrates how to set up a basic Elysia application with the @elysia/openapi plugin, defining a GET endpoint for users and specifying the response schema. Visit http://localhost:3000/openapi for the generated documentation. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' new Elysia() .use(openapi()) .get('/users', () => [], { response: t.Array(t.Object({ id: t.Number(), name: t.String() })) }) .listen(3000) // Visit http://localhost:3000/openapi for documentation ``` -------------------------------- ### Document Request/Response Examples Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/best-practices.md Define request and response examples directly within route details for clarity. ```typescript .post('/users', () => ({}), { detail: { description: 'Create a new user account', examples: { request: { name: 'John Doe', email: 'john@example.com' }, response: { id: 123, name: 'John Doe', email: 'john@example.com' } } } }) ``` -------------------------------- ### AdditionalReference Example Usage Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/types.md Example showing how to provide additional OpenAPI schema information for routes, including parameters, query, headers, body, and responses. ```typescript { '/users': { get: { params: t.Never(), query: t.Object({ limit: t.Optional(t.Number()) }), headers: t.Object({ 'x-api-key': t.String() }), body: t.Never(), response: { 200: t.Array(UserSchema) } } } } ``` -------------------------------- ### Swagger UI Options Usage Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Demonstrates how to import and use SwaggerUIOptions for configuration. Ensure the types are imported from '@elysia/openapi/swagger/types'. ```typescript import type { SwaggerUIOptions, PluginsOptions, SwaggerUIPlugin } from '@elysia/openapi/swagger/types' const swaggerConfig: SwaggerUIOptions = { docExpansion: 'list', deepLinking: true } ``` -------------------------------- ### ESM Module Structure Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Illustrates how to import Elysia OpenAPI modules using ES Modules `import` syntax. ```typescript import { openapi, fromTypes, toOpenAPISchema } from '@elysia/openapi' import { SwaggerUIRender } from '@elysia/openapi/swagger' import { ScalarRender } from '@elysia/openapi/scalar' ``` -------------------------------- ### CommonJS Module Structure Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Demonstrates how to import Elysia OpenAPI modules using CommonJS `require` syntax. ```typescript const { openapi, fromTypes, toOpenAPISchema } = require('@elysia/openapi') const { SwaggerUIRender } = require('@elysia/openapi/swagger') const { ScalarRender } = require('@elysia/openapi/scalar') ``` -------------------------------- ### Basic Elysia OpenAPI Setup Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/openapi.md Integrates the OpenAPI plugin with default settings (Scalar UI) into an Elysia application. Exposes OpenAPI documentation at the default '/openapi' path. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' const app = new Elysia() .use(openapi()) .get('/users', () => ({ users: [] }), { response: t.Array(t.Object({ id: t.Number(), name: t.String() })) }) .listen(3000) // OpenAPI documentation available at http://localhost:3000/openapi ``` -------------------------------- ### Combined with Optional Headers Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/withHeaders.md Example of using `withHeaders` to include both optional and default headers in a response schema. ```APIDOC ## GET /items ### Description Retrieves items with optional cursor header and default content-type. ### Method GET ### Endpoint /items ### Parameters #### Response ##### Success Response (200) - **content** (string) - The item content. ##### Headers - **x-cursor** (string) - Optional - Pagination cursor for next page. - **content-type** (string) - Defaults to 'application/json'. ### Request Example (Not applicable for this example) ### Response Example ```json { "content": "data" } ``` ``` -------------------------------- ### MapJsonSchema Example Usage Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/types.md Example demonstrating how to map vendor schema libraries to their respective JSON Schema conversion functions. ```typescript { zod: z.toJSONSchema, valibot: toJsonSchema, effect: JSONSchema.make } ``` -------------------------------- ### Minimal Elysia OpenAPI Setup Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/integration-guide.md Integrate the @elysia/openapi plugin with a basic Elysia application. Documentation is available at '/openapi' and the JSON spec at '/openapi/json'. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' const app = new Elysia() .use(openapi()) .get('/hello', () => 'Hello World') .listen(3000) // Documentation available at http://localhost:3000/openapi // JSON spec at http://localhost:3000/openapi/json ``` -------------------------------- ### OpenAPI Schema Exports Usage Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Shows how to import OpenAPI schema generation functions from the '@elysia/openapi' or '@elysia/openapi/openapi' paths. ```typescript import { toOpenAPISchema, withHeaders, getPossiblePath, enumToOpenApi, unwrapSchema } from '@elysia/openapi' // or import { toOpenAPISchema, withHeaders, getPossiblePath, enumToOpenApi, unwrapSchema } from '@elysia/openapi/openapi' ``` -------------------------------- ### Reusing Headers Across Multiple Routes Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/withHeaders.md Shows how to define common headers once and reuse them across different response schemas for multiple routes. ```APIDOC ## Multiple Routes with Reused Headers ### Description Demonstrates reusing a common set of headers across different API routes and response types. ### Routes #### GET /users/:id ##### Description Retrieves user details with common headers. ##### Response - **id** (number) - The user's ID. - **name** (string) - The user's name. ##### Headers - **x-api-version** (string) - API version. Defaults to '1.0'. - **x-powered-by** (string) - The technology used. Defaults to 'Elysia'. #### POST /users ##### Description Handles user creation or update, returning an error with common headers. ##### Response - **error** (string) - Description of the error. - **code** (number) - The error code. ##### Headers - **x-api-version** (string) - API version. Defaults to '1.0'. - **x-powered-by** (string) - The technology used. Defaults to 'Elysia'. ### Request Example (Not applicable for this example) ### Response Example For GET /users/:id: ```json { "id": 1, "name": "John" } ``` For POST /users: ```json { "error": "Invalid input", "code": 400 } ``` ``` -------------------------------- ### Render Swagger UI HTML Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Example of rendering the Swagger UI HTML using `SwaggerUIRender` with specified configuration options. ```typescript // Render Swagger UI HTML const html = SwaggerUIRender( { title: 'API', description: 'My API', version: '1.0.0' }, { url: '/openapi/json', dom_id: '#swagger-ui', version: '4.18.2' } ) ``` -------------------------------- ### Configure Swagger UI with a String Theme Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/swagger.md This example shows how to apply a custom CSS theme to Swagger UI by providing a direct URL to a CSS file. This is useful for applying a specific visual style to the documentation interface. ```typescript new Elysia() .use( openapi({ provider: 'swagger-ui', swagger: { theme: 'https://unpkg.com/swagger-ui-dist@4.18.2/swagger-ui.css' } }) ) .listen(3000) ``` -------------------------------- ### Complex Headers Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/withHeaders.md Illustrates using `withHeaders` to define multiple complex headers, including a default value for `cache-control`. ```APIDOC ## GET /users/:id ### Description Retrieves user information with complex response headers. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Response ##### Success Response (200) - **id** (number) - The user's ID. - **name** (string) - The user's name. ##### Headers - **x-request-id** (string) - Request tracking ID. - **x-ratelimit-remaining** (number) - Remaining API calls in current window. - **cache-control** (string) - Cache control directives. Defaults to 'no-cache'. ### Request Example (Not applicable for this example) ### Response Example ```json { "id": 1, "name": "John" } ``` ``` -------------------------------- ### Date Property Transformation Example Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/swagger.md Illustrates the automatic transformation of Prisma-style nullable date unions in response schemas to simplified date-time formats by the OpenAPI plugin. ```typescript // Input: createdAt with anyOf union (Prisma-style) { createdAt: { anyOf: [ { type: 'string', format: 'date-time' }, { type: 'null' } ] } } // Output: Simplified date-time format { createdAt: { type: 'string', format: 'date-time' } } ``` -------------------------------- ### Configure OpenAPI References with fromTypes Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Example of using `fromTypes` within the `openapi` plugin configuration to reference generated schemas. ```typescript .use(openapi({ references: fromTypes('src/index.ts', { tsconfigPath: 'tsconfig.json' }) })) ``` -------------------------------- ### Render Scalar API Reference UI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Example of directly rendering the Scalar API Reference HTML using `ScalarRender`. ```typescript const html = ScalarRender( { title: 'API', description: 'My API', version: '1.0.0' }, { url: '/openapi/json', version: 'latest', cdn: 'https://cdn.jsdelivr.net/npm/@scalar/api-reference@latest/dist/browser/standalone.min.js' } ) ``` -------------------------------- ### Define Route with Request and Response Schemas Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/integration-guide.md Example of defining a POST route in Elysia with explicit request body and response schemas using `t.Object`. ```typescript .post( '/users', ({ body }) => body, { body: t.Object({ name: t.String(), email: t.String() }), response: t.Object({ id: t.Number(), name: t.String(), email: t.String() }) } ) ``` -------------------------------- ### Select OpenAPI Provider Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/configuration.md Selects which documentation frontend to use. Options include 'scalar' (default), 'swagger-ui', or null to expose only the JSON spec. ```typescript // Use Scalar API Reference (default) .use(openapi({ provider: 'scalar' })) // Use Swagger UI .use(openapi({ provider: 'swagger-ui' })) // Expose only JSON spec, no UI .use(openapi({ provider: null })) ``` -------------------------------- ### Configure OpenAPI UI Path Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/configuration.md Sets the HTTP path where the documentation UI will be exposed. The default path is '/openapi'. ```typescript new Elysia() .use(openapi({ path: '/api/docs' })) .listen(3000) // UI available at http://localhost:3000/api/docs ``` -------------------------------- ### Transform Date Properties in Schema Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Example of using `transformDateProperties` to modify date fields within an OpenAPI schema object. ```typescript // Transform date properties in schemas const transformed = transformDateProperties(schema) ``` -------------------------------- ### Configuring Custom Scalar CDN and CSS Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/scalar.md Illustrates how to specify a custom CDN path for the Scalar API Reference bundle and load custom CSS from a file. ```typescript new Elysia() .use( openapi({ scalar: { cdn: '/public/scalar/standalone.min.js', customCss: fs.readFileSync('./custom-scalar.css', 'utf-8') } }) ) .listen(3000) ``` -------------------------------- ### Document Query Parameters with Descriptions Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/best-practices.md Shows how to document query parameters for a search endpoint, including descriptions for the search term, limit, and offset. It also demonstrates setting default values and constraints for these parameters. ```typescript .get('/search', () => ({}), { query: t.Object({ q: t.String({ description: 'Search query term' }), limit: t.Optional(t.Number({ description: 'Maximum results to return', minimum: 1, maximum: 100, default: 20 })), offset: t.Optional(t.Number({ description: 'Results offset for pagination', minimum: 0, default: 0 })) }) }) ``` -------------------------------- ### OpenAPI with Zod Schema Mapping Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/openapi.md Enables mapping of Zod schemas to JSON Schema for OpenAPI documentation. This requires Zod to be installed and configured via `mapJsonSchema.zod`. ```typescript import { Elysia } from 'elysia' import { openapi } from '@elysia/openapi' import * as z from 'zod' new Elysia() .use( openapi({ mapJsonSchema: { zod: z.toJSONSchema } }) ) .post( '/users', ({ body }) => body, { body: z.object({ name: z.string(), email: z.string().email() }), response: z.object({ id: z.number(), name: z.string(), email: z.string() }) } ) .listen(3000) ``` -------------------------------- ### Basic Elysia App with Scalar UI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/scalar.md Demonstrates how to integrate the Scalar API Reference UI into an Elysia application using the openapi plugin with default Scalar configuration. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' new Elysia() .use( openapi({ provider: 'scalar', scalar: { theme: 'kepler', darkMode: true, cdn: 'https://cdn.jsdelivr.net/npm/@scalar/api-reference@latest/dist/browser/standalone.min.js' } }) ) .get('/api', () => ({})) .listen(3000) ``` -------------------------------- ### Document Multiple API Versions with OpenAPI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/integration-guide.md Configure OpenAPI documentation to include information and servers for multiple API versions, allowing users to select the desired version. ```typescript const v1 = new Elysia({ prefix: '/v1' }) .get('/users', () => []) const v2 = new Elysia({ prefix: '/v2' }) .get('/users', () => ({}), { response: t.Object({ data: t.Array(t.Object({})) }) }) new Elysia() .use( openapi({ documentation: { info: { title: 'API', version: '2.0.0' }, servers: [ { url: '/v1', description: 'Version 1' }, { url: '/v2', description: 'Version 2 (current)' } ] } }) ) .use(v1) .use(v2) .listen(3000) ``` -------------------------------- ### Main Plugin Exports Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md The primary entry point for the @elysia/openapi plugin, used to integrate OpenAPI schema generation with Elysia. ```APIDOC ## Main Plugin Exports ### Description Provides the main `openapi` function to be used as an Elysia plugin for generating OpenAPI schemas. ### Usage ```typescript // ESM import { openapi } from '@elysia/openapi' // CJS const { openapi } = require('@elysia/openapi') // Default import import openapi from '@elysia/openapi' ``` ### Exports - `openapi`: Function to enable OpenAPI integration. - `fromTypes`: Utility for generating schemas from TypeScript types. - `toOpenAPISchema`: Function to convert an Elysia app to an OpenAPI schema object. - `withHeaders`: Utility for defining schema with headers. - `ElysiaOpenAPIConfig`: Type for configuring the OpenAPI plugin. ``` -------------------------------- ### Schema Generation with Zod Vendor Mapping Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/toOpenAPISchema.md Generates an OpenAPI schema using Zod for request body and response validation, mapping Zod schemas to OpenAPI components. This requires the zod library to be installed. ```typescript import { Elysia } from 'elysia' import { toOpenAPISchema } from '@elysia/openapi' import * as z from 'zod' const app = new Elysia() .post('/users', ({ body }) => body, { body: z.object({ name: z.string() }), response: z.object({ id: z.number(), name: z.string() }) }) const schema = toOpenAPISchema(app, undefined, undefined, { zod: z.toJSONSchema }) ``` -------------------------------- ### Enable OpenAPI Documentation Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/README.md Use this snippet to enable the OpenAPI documentation UI and JSON spec endpoints. Visit /openapi for the UI and /openapi/json for the specification. ```typescript .use(openapi()) // Visit /openapi for UI, /openapi/json for spec ``` -------------------------------- ### OpenAPI with Documentation Metadata Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/openapi.md Configures the OpenAPI plugin with custom API metadata, including title, description, version, and server information. This enhances the generated OpenAPI specification. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' new Elysia() .use( openapi({ documentation: { info: { title: 'My API', description: 'Production API', version: '1.0.0' }, servers: [ { url: 'https://api.example.com', description: 'Production' }, { url: 'https://dev.example.com', description: 'Development' } ] } }) ) .get('/status', () => ({ ok: true })) .listen(3000) ``` -------------------------------- ### Basic Elysia App with OpenAPI and Swagger UI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/swagger.md This snippet demonstrates how to set up a basic Elysia application and integrate the OpenAPI plugin with Swagger UI. It configures Swagger UI with specific options like version, autoDarkMode, docExpansion, and filter. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' new Elysia() .use( openapi({ provider: 'swagger-ui', swagger: { version: '4.18.2', autoDarkMode: true, docExpansion: 'list', filter: true } }) ) .get('/api', () => ({})) .listen(3000) ``` -------------------------------- ### Import Header Utility Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import the `withHeaders` utility for defining schema headers. ```typescript import { withHeaders } from '@elysia/openapi' ``` -------------------------------- ### Configure OpenAPI Multi-Provider Support Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/best-practices.md Dynamically select and configure different OpenAPI UI providers (e.g., Scalar, Swagger UI) based on environment variables. This allows you to customize the look and feel of your API documentation. ```typescript const provider = process.env.OPENAPI_PROVIDER as 'scalar' | 'swagger-ui' openapi({ provider: provider || 'scalar', scalar: { theme: 'kepler' }, swagger: { theme: 'https://unpkg.com/swagger-ui-dist@4.18.2/swagger-ui.css' } }) ``` -------------------------------- ### openapi() Plugin Configuration Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/openapi.md The main openapi() plugin function allows for automatic generation of OpenAPI 3.0.3 documentation. It introspects Elysia routes and can serve an interactive UI like Scalar or Swagger UI. The function signature and available parameters are detailed below. ```APIDOC ## openapi() Plugin Configuration ### Description This function is the main entry point for the Elysia OpenAPI plugin. It enables automatic OpenAPI documentation generation for your Elysia application, introspecting routes and providing an interactive UI. ### Function Signature ```typescript const openapi = < const Enabled extends boolean = true, const Path extends string = '/openapi' >({ enabled, path, provider, specPath, documentation, exclude, swagger, scalar, references, mapJsonSchema, embedSpec }: ElysiaOpenAPIConfig = {}): Elysia ``` ### Parameters #### Plugin Options - **enabled** (`boolean`): Enable or disable the plugin. Default: `true`. - **path** (`string`): The HTTP path where the OpenAPI documentation UI will be exposed. Default: `'/openapi'`. - **provider** (`'scalar' | 'swagger-ui' | null`): The UI provider to use. Set to `null` to disable the frontend UI. Default: `'scalar'`. - **specPath** (`string`): The HTTP path where the OpenAPI JSON specification will be exposed. Default: `'${path}/json'`. - **documentation** (`Partial`): OpenAPI documentation metadata (info, tags, servers, etc.). Default: `{}`. - **exclude** (`ExcludeConfig`): Configuration for excluding routes or methods from documentation. - **swagger** (`SwaggerUIConfig`): Swagger UI specific configuration options. - **scalar** (`ScalarConfig`): Scalar API Reference configuration options. - **references** (`AdditionalReferences`): Additional OpenAPI schema references for endpoints. - **mapJsonSchema** (`MapJsonSchema`): Functions for vendor schema to JSON Schema conversion (e.g., zod, valibot). - **embedSpec** (`boolean`): Embed OpenAPI schema in HTML response. Not recommended. Default: `false`. ### Return Type Returns an Elysia plugin instance that can be chained with `.use()`. ``` -------------------------------- ### Sub-path Imports for Tree-Shaking Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Demonstrates importing specific modules from sub-paths for optimized bundle sizes, contrasting with importing all from the main export. ```typescript // Main export includes everything import { openapi, fromTypes, toOpenAPISchema, withHeaders, ScalarRender, SwaggerUIRender, transformDateProperties } from '@elysia/openapi' // Or use sub-path exports for tree-shaking import { SwaggerUIRender } from '@elysia/openapi/swagger' import { ScalarRender } from '@elysia/openapi/scalar' ``` -------------------------------- ### Import Swagger UI Options Type Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import the `SwaggerUIOptions` type for configuring Swagger UI. ```typescript import type { SwaggerUIOptions } from '@elysia/openapi/swagger/types' ``` -------------------------------- ### Configure Swagger UI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/configuration.md Configure Swagger UI by setting 'provider' to 'swagger-ui' and using the 'swagger' object for options. This includes version, CDN, theme, dark mode, and various UI behaviors. ```typescript new Elysia() .use(openapi({ provider: 'swagger-ui', swagger: { version: '4.18.2', cdn: 'https://unpkg.com/swagger-ui-dist@4.18.2/swagger-ui-bundle.js', theme: 'https://unpkg.com/swagger-ui-dist@4.18.2/swagger-ui.css', autoDarkMode: true, deepLinking: true, docExpansion: 'list', filter: true, tryItOutEnabled: true, displayOperationId: false, validatorUrl: 'https://validator.swagger.io' } })) .listen(3000) ``` -------------------------------- ### Documenting Custom Response Headers Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/integration-guide.md Use the `withHeaders` helper to document custom response headers like 'x-request-id' and 'x-ratelimit-remaining'. This requires importing `withHeaders` from '@elysiajs/openapi'. ```typescript import { withHeaders } from '@elysiajs/openapi' const userResponse = withHeaders( t.Object({ id: t.Number(), name: t.String() }), { 'x-request-id': t.String(), 'x-ratelimit-remaining': t.Number() } ) new Elysia() .use(openapi()) .get('/users/:id', () => ({ id: 1, name: 'John' }), { response: userResponse }) .listen(3000) ``` -------------------------------- ### Use Swagger UI Instead of Scalar Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/README.md Configure the plugin to use Swagger UI as the documentation provider instead of the default Scalar UI. ```typescript .use(openapi({ provider: 'swagger-ui' })) ``` -------------------------------- ### Configure Swagger UI with Dark/Light Mode Theming Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/swagger.md This snippet illustrates how to configure Swagger UI to support both light and dark modes using separate CSS files. It also enables autoDarkMode to automatically switch themes based on system preferences. ```typescript new Elysia() .use( openapi({ provider: 'swagger-ui', swagger: { theme: { light: 'https://unpkg.com/swagger-ui-dist@4.18.2/swagger-ui.css', dark: 'https://unpkg.com/swagger-ui-dist@4.18.2/swagger-ui.css' // Custom dark CSS }, autoDarkMode: true } }) ) .listen(3000) ``` -------------------------------- ### Configure Syntax Highlighting in Swagger UI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/swagger.md Enables syntax highlighting in Swagger UI and sets a specific theme. Supported themes include 'agate', 'arta', 'idea', 'monokai', 'nord', 'obsidian', and 'tomorrow-night'. ```typescript new Elysia() .use( openapi({ provider: 'swagger-ui', swagger: { syntaxHighlight: { activate: true, theme: 'monokai' // 'agate', 'arta', 'idea', 'monokai', 'nord', 'obsidian', 'tomorrow-night' } } }) ) .listen(3000) ``` -------------------------------- ### Import Main Elysia OpenAPI Plugin Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import the main Elysia OpenAPI plugin for CommonJS and ES Module environments. ```typescript import { openapi } from '@elysia/openapi' import { openapi } from '@elysia/openapi' // ESM ``` ```javascript const { openapi } = require('@elysia/openapi') // CJS ``` -------------------------------- ### Document Request Headers for Authentication Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/best-practices.md Demonstrates how to document required request headers, such as an 'authorization' header for a Bearer token. This clarifies authentication requirements for API consumers. ```typescript .post('/users', () => ({}), { headers: t.Object({ authorization: t.String({ description: 'Bearer token' }) }) }) // Authentication requirements appear in documentation ``` -------------------------------- ### Default Elysia OpenAPI Plugin Configuration Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/configuration.md Shows the default configuration object when the `openapi()` plugin is used without any arguments. This provides a baseline for understanding the plugin's default behavior. ```json { "enabled": true, "path": "/openapi", "provider": "scalar", "specPath": "/openapi/json", "embedSpec": false, "documentation": {}, "exclude": { "methods": ["options"], "paths": [], "staticFile": true, "tags": [] } } ``` -------------------------------- ### Elysia OpenAPI Type Imports Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/types.md Demonstrates how to import necessary types from the '@elysia/openapi' package and its submodules for use in your project. ```typescript import type { ElysiaOpenAPIConfig, OpenAPIProvider, MapJsonSchema, AdditionalReference, AdditionalReferences } from '@elysia/openapi' import type { OpenAPIGeneratorOptions } from '@elysia/openapi/gen' import type { SwaggerUIOptions } from '@elysia/openapi/swagger/types' ``` -------------------------------- ### Elysia OpenAPI with Type Definitions Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/integration-guide.md Set up Elysia with @elysia/openapi, defining route parameters and response schemas using Elysia's type system for automatic OpenAPI spec generation. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' const app = new Elysia() .use(openapi()) .get( '/users/:id', ({ params: { id } }) => ({ id, name: 'John' }), { params: t.Object({ id: t.String() }), response: t.Object({ id: t.String(), name: t.String() }) } ) .listen(3000) // OpenAPI spec automatically generated from type definitions ``` -------------------------------- ### Import Swagger UI Functions Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import `SwaggerUIRender` and `transformDateProperties` for Swagger UI integration and schema transformation. ```typescript import { SwaggerUIRender, transformDateProperties } from '@elysia/openapi/swagger' ``` -------------------------------- ### Use Descriptions for Schema Fields Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/best-practices.md Illustrates adding descriptive text to schema fields using the `description` property. This enhances the OpenAPI documentation by providing clear explanations for each field's purpose. ```typescript const UserSchema = t.Object({ id: t.Number({ description: 'Unique user identifier' }), name: t.String({ description: 'Full name of the user' }), email: t.String({ format: 'email', description: 'Email address for contact' }), createdAt: t.String({ format: 'date-time', description: 'Account creation timestamp' }) }) ``` -------------------------------- ### Scalar Theme Exports Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Provides theme configuration constants for customizing the Scalar UI. ```APIDOC ## Scalar Theme Exports: @elysia/openapi/scalar/theme ### Description Exposes CSS constants for customizing the appearance of the Scalar API Reference UI, including light and dark mode variables. ### Usage ```typescript import { openapi } from '@elysia/openapi' .use(openapi({ scalar: { customCss: ` .light-mode { --scalar-color-accent: #ff6b6b; } .dark-mode { --scalar-color-accent: #ff8787; } ` } })) ``` ``` -------------------------------- ### OpenAPIProvider Type Alias Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/types.md Type alias for supported UI providers. Selects which documentation UI to render: 'scalar', 'swagger-ui', or null for no frontend. ```typescript type OpenAPIProvider = 'scalar' | 'swagger-ui' | null ``` -------------------------------- ### Import Schema Generation Utilities Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import the `toOpenAPISchema` function for converting an Elysia app instance into an OpenAPI schema object. ```typescript import { toOpenAPISchema } from '@elysia/openapi' ``` -------------------------------- ### Customizing Scalar UI Theme with CSS Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/scalar.md Shows how to apply custom CSS to the Scalar API Reference UI to override default themes and branding, including light and dark mode specific styles. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' new Elysia() .use( openapi({ scalar: { customCss: ` .light-mode { --scalar-color-accent: #ff0000; } .dark-mode { --scalar-color-accent: #ffaa00; } ` } }) ) .get('/api', () => ({})) .listen(3000) ``` -------------------------------- ### Customize OpenAPI Documentation Info Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/README.md Customize the OpenAPI documentation metadata, such as the API title and version, and server URLs. ```typescript .use(openapi({ documentation: { info: { title: 'My API', version: '1.0.0' }, servers: [ { url: 'https://api.example.com' } ] } })) ``` -------------------------------- ### OpenAPI with Custom Scalar Configuration Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/openapi.md Applies custom configurations to the Scalar UI, such as theme, dark mode, and CDN URL. This allows for branding and customization of the OpenAPI documentation interface. ```typescript import { Elysia, t } from 'elysia' import { openapi } from '@elysia/openapi' new Elysia() .use( openapi({ scalar: { theme: 'kepler', darkMode: true, cdn: 'https://custom-cdn.example.com/scalar.min.js' } }) ) .get('/api', () => ({})) .listen(3000) ``` -------------------------------- ### Response Schema Formats in OpenAPI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/toOpenAPISchema.md Illustrates the different formats supported for defining response schemas, including single schemas, status-keyed objects, string references, and combined formats. ```typescript response: t.Object({...}) // treated as 200 response ``` ```typescript response: { 200: schema, 404: schema } ``` ```typescript response: 'User' // references a component schema ``` ```typescript response: { 200: 'User', 404: 'Error' } ``` -------------------------------- ### Structure Routes with Tags Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/best-practices.md Organize your API endpoints by grouping related routes under specific tags. This improves the clarity and navigability of your documentation UI. ```typescript new Elysia() .use( openapi({ documentation: { tags: [ { name: 'users', description: 'User management' }, { name: 'products', description: 'Product catalog' }, { name: 'orders', description: 'Order management' } ] } }) ) .get('/users', () => [], { detail: { tags: ['users'] } }) .get('/users/:id', () => ({}), { detail: { tags: ['users'] } }) .post('/users', () => ({}), { detail: { tags: ['users'] } }) .get('/products', () => [], { detail: { tags: ['products'] } }) .listen(3000) // Documentation UI groups endpoints by tag ``` -------------------------------- ### Import Type Generation Utilities Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import the `fromTypes` function for generating OpenAPI schemas from TypeScript types. ```typescript import { fromTypes } from '@elysia/openapi' ``` -------------------------------- ### Generate All Possible Paths for a Route Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/utilities.md Generates all possible path variations for a given route string, handling optional parameters marked with '?'. Useful for documenting routes with optional segments. ```typescript import { getPossiblePath } from '@elysia/openapi' // Single optional parameter getPossiblePath('/users/:id?') // Returns: ['/users/:id?', '/users/'] // Multiple optional parameters getPossiblePath('/posts/:year?/:month?/:day?') // Returns: ['/posts/:year?/:month?/:day?', '/posts/:year?/:month?/', '/posts/:year?/', '/posts/'] ``` -------------------------------- ### Basic Schema Generation with Elysia and OpenAPI Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/toOpenAPISchema.md Generates a basic OpenAPI schema from an Elysia application instance. This is useful for documenting your API endpoints. ```typescript import { Elysia, t } from 'elysia' import { toOpenAPISchema } from '@elysia/openapi' const app = new Elysia() .get('/users/:id', ({ params: { id } }) => ({ id }), { params: t.Object({ id: t.String() }), response: t.Object({ id: t.String() }) }) const schema = toOpenAPISchema(app) console.log(schema.paths) // Outputs OpenAPI path definitions ``` -------------------------------- ### Import Default Export Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import the default export of the Elysia OpenAPI plugin. ```typescript import openapi from '@elysia/openapi' ``` -------------------------------- ### Basic Usage of fromTypes() Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/api-reference/fromTypes.md Use `fromTypes()` with default options to generate OpenAPI references from the default 'src/index.ts' file. This is suitable for simple Elysia applications. ```typescript import { Elysia, t } from 'elysia' import { openapi, fromTypes } from '@elysia/openapi' const app = new Elysia() .use( openapi({ references: fromTypes() }) ) .get('/', () => 'Hello') .post('/users', ({ body }) => body) .listen(3000) ``` -------------------------------- ### Document with Zod Schema Mapping Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/README.md Integrate Zod schemas for documentation by mapping them using `z.toJSONSchema`. This requires importing the Zod library. ```typescript import * as z from 'zod' .use(openapi({ mapJsonSchema: { zod: z.toJSONSchema } })) ``` -------------------------------- ### Import OpenAPI Type Definitions Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import type definitions related to Elysia OpenAPI configuration. ```typescript import type { ElysiaOpenAPIConfig } from '@elysia/openapi' ``` -------------------------------- ### Import Type Definitions from @elysia/openapi/types Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/module-exports.md Import various type definitions from the dedicated types module for OpenAPI. ```typescript import type { ElysiaOpenAPIConfig, OpenAPIProvider, MapJsonSchema, AdditionalReference, AdditionalReferences } from '@elysia/openapi/types' ``` -------------------------------- ### SwaggerUIOptions Interface Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/types.md Defines the complete configuration options for integrating Swagger UI with Elysia. Use this to customize the appearance and behavior of the Swagger documentation interface. ```typescript interface SwaggerUIOptions { // Core configUrl?: string dom_id?: string spec?: { [propName: string]: any } url?: string urls?: Array<{ url: string; name: string }> // Plugin system layout?: string pluginsOptions?: PluginsOptions plugins?: SwaggerUIPlugin[] presets?: SwaggerUIPlugin[] // Display deepLinking?: boolean displayOperationId?: boolean defaultModelsExpandDepth?: number defaultModelExpandDepth?: number defaultModelRendering?: 'example' | 'model' displayRequestDuration?: boolean docExpansion?: 'list' | 'full' | 'none' filter?: boolean | string maxDisplayedTags?: number operationsSorter?: SorterLike showExtensions?: boolean showCommonExtensions?: boolean tagsSorter?: SorterLike useUnsafeMarkdown?: boolean onComplete?: (() => any) syntaxHighlight?: false | { activate?: boolean; theme?: string } tryItOutEnabled?: boolean requestSnippets?: { generators?: any; defaultExpanded?: boolean; languagesMask?: string[] } // Network oauth2RedirectUrl?: string requestInterceptor?: ((a: Request) => Request | Promise) responseInterceptor?: ((a: Response) => Response | Promise) showMutatedRequest?: boolean supportedSubmitMethods?: SupportedHTTPMethods[] validatorUrl?: string withCredentials?: boolean // Macros modelPropertyMacro?: ((propName: Readonly) => any) parameterMacro?: ((operation: Readonly, parameter: Readonly) => any) // Authorization persistAuthorization?: boolean } ``` -------------------------------- ### Configure OpenAPI Documentation Metadata Source: https://github.com/elysiajs/elysia-openapi/blob/main/_autodocs/configuration.md Configures OpenAPI document metadata including title, description, servers, tags, and more, directly mapping to the OpenAPI 3.0.3 specification. ```typescript new Elysia() .use(openapi({ documentation: { info: { title: 'My API', description: 'API documentation', version: '1.0.0', contact: { name: 'API Support', url: 'https://example.com/support' }, license: { name: 'MIT', url: 'https://opensource.org/licenses/MIT' } }, servers: [ { url: 'https://api.example.com', description: 'Production' }, { url: 'https://dev.example.com', description: 'Development' } ], tags: [ { name: 'users', description: 'User management endpoints' }, { name: 'products', description: 'Product catalog endpoints' } ], externalDocs: { url: 'https://docs.example.com', description: 'External documentation' } } })) .listen(3000) ```