Elysia OpenAPI Plugin

repository·main·Indexed 41 days ago

https://github.com/elysiajs/elysia-openapi

A plugin for the ElysiaJS framework that automatically generates and serves OpenAPI (Swagger) documentation based on route definitions and TypeBox schemas. Version 1.4.16 supports OpenAPI versions 3.0.x and 3.1.x, and provides built-in integration for Scalar and Swagger UI documentation frontends.

Tokens
6.6K
Snippets
17
Records
22
Agent score
50%

What's inside Elysia OpenAPI

  1. Configure @elysia/openapi options

    main

    The openapi() function accepts a configuration object to customize the generated documentation.

    Core Configuration

    • enabled: (default: true) Enable or disable the plugin.
    • openapiVersion: (default: '3.1.2') The OpenAPI document version to emit. Supports 3.0.x and 3.1.x.
    • path: (default: '/openapi') The endpoint to expose the OpenAPI documentation frontend.
    • specPath: (default: '/${path}/json') The endpoint to expose the OpenAPI specification in JSON format.
    • provider: (default: 'scalar') The documentation frontend provider. Options are scalar, swagger, or null to disable the frontend.

    Exclude Routes

    Use the exclude object to hide specific parts of your API from the documentation:

    • exclude.methods: A list of HTTP methods to exclude.
    • exclude.paths: A list of paths to exclude.
    • exclude.staticFile: (default: true) Exclude static file routes.
    • exclude.tags: A list of tags to exclude.

    Documentation & References

    • documentation: Object containing OpenAPI documentation information.
    • references: Additional OpenAPI references for each endpoint.

    Provider Specific Config

    • scalar: Configuration for the Scalar provider (follows Scalar config).
    • swagger: Configuration for the SwaggerUI provider (follows Swagger config).
  2. Embed the OpenAPI spec in the documentation UI

    main

    By default, the documentation UI fetches the OpenAPI specification from the specPath via a network request. If you set embedSpec: true, the plugin will inject the entire JSON specification directly into the HTML response. This is useful for reducing network requests or when working in environments like Cloudflare Workers where you might want to minimize external fetches.

    app.use(openapi({
        embedSpec: true
    }))
  3. Basic usage of @elysia/openapi

    main

    To use the plugin, import openapi from @elysia/openapi and register it using .use(openapi()) on your Elysia instance. The plugin automatically generates documentation based on your route definitions, including schemas provided via Elysia's t (TypeBox) validation. By default, the documentation frontend is available at /openapi.

    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)
  4. Configure the openapi() plugin options

    main

    The openapi() function accepts a configuration object of type ElysiaOpenAPIConfig.

    Configuration Options

    OptionTypeDefaultDescription
    enabledbooleantrueWhether the plugin is active.
    pathstring'/openapi'The URL path where the documentation UI is served.
    provider'scalar' | 'swagger-ui' | nullThe UI provider. Use null to disable the UI and only serve the JSON spec.
    specPathstring'{path}/json'The URL path where the raw OpenAPI JSON specification is served.
    openapiVersionOpenAPIVersion'3.1.2'The OpenAPI version to use in the generated spec.
    documentationobject{}Custom metadata for the OpenAPI document (e.g., info, tags, components).
    excludeobjectundefinedOptions to filter out parts of the documentation (see Exclude documentation).
    swaggerobject{}Configuration specific to the swagger-ui provider.
    scalarobject{}Configuration specific to the scalar provider.
    embedSpecbooleanfalseIf true, the OpenAPI specification is embedded directly into the HTML of the documentation page.
    mapJsonSchemafunctionundefinedA function to map JSON schemas during generation.
    referencesobjectundefinedCustom references for the OpenAPI schema.

    Exclude documentation

    Use the exclude object to hide specific parts of your API from the documentation:

    • exclude.methods: Array of HTTP methods to exclude.
    • exclude.paths: Array of path strings to exclude.
    • exclude.staticFile: Exclude static file routes.
    • exclude.tags: Array of tag names to exclude.
    app.use(openapi({
        path: '/docs',
        provider: 'swagger-ui',
        documentation: {
            info: {
                title: 'My API',
                version: '1.0.0'
            }
        },
        exclude: {
            tags: ['internal']
        }
    }))
  5. Configure ElysiaOpenAPIConfig

    main

    The ElysiaOpenAPIConfig interface defines the configuration options for the @elysiajs/openapi plugin. It allows you to control the OpenAPI version, documentation content, endpoint paths, provider selection (Scalar or Swagger UI), and exclusion rules for specific methods, paths, or tags.

    // Example configuration structure
    openapi({
      enabled: true,
      openapiVersion: '3.1.0',
      path: '/docs',
      provider: 'scalar',
      documentation: {
        info: { title: 'My API', version: '1.0.0' }
      },
      exclude: {
        methods: ['DELETE'],
        paths: ['/internal/.*'],
        tags: ['admin']
      }
    })
  6. Reference the OpenAPI JSON specification path

    main
    The plugin exposes the raw OpenAPI JSON specification at a specific endpoint. By default, this is located at /${path}/json, where path is your configured documentation endpoint (defaulting to /openapi). You can override this using the specPath option.
  7. Exclude endpoints and methods from OpenAPI

    main

    Use the exclude object in your configuration to prevent certain parts of your API from appearing in the generated OpenAPI documentation.

    • methods: An array of strings representing HTTP methods to exclude (e.g., ['DELETE']).
    • paths: A string, RegExp, or array of strings/RegExps to exclude specific paths.
    • tags: An array of strings to exclude specific tags.
    • staticFile: A boolean to determine if static files should be excluded (defaults to true).
    openapi({
      exclude: {
        methods: ['POST'],
        paths: [/^\/private/, '/health'],
        tags: ['internal']
      }
    })
  8. Define OpenAPI version and documentation

    main

    You can explicitly set the OpenAPI specification version and provide custom documentation metadata.

    • openapiVersion: Set the version using the format `3.0.${number}` or `3.1.${number}` (e.g., '3.1.2').
    • documentation: An object containing partial OpenAPIV3 or OpenAPIV3_1 document properties (like info, servers, etc.). Note that x-express-openapi-additional-middleware and x-express-openapi-validation-strict are omitted from this type.
  9. Configure the OpenAPI provider (Scalar or Swagger UI)

    main

    You can choose between scalar (default) and swagger-ui using the provider option. Each provider has its own specific configuration block:

    • Scalar: Use the scalar key to pass ApiReferenceConfiguration. You can also specify a version for the CDN bundle or a custom cdn path (e.g., a local file or a specific unpkg URL).
    • Swagger UI: Use the swagger key to pass options to SwaggerUIBundle. Supported options include theme (string or light/dark object), version (default 4.18.2), autoDarkMode, and cdn for custom bundle paths. Note that functional options like requestInterceptor are not supported.
    // Scalar configuration example
    openapi({
      provider: 'scalar',
      scalar: {
        version: 'latest',
        cdn: 'https://unpkg.com/@scalar/api-reference@1.13.10/dist/browser/standalone.js'
      }
    })
    
    // Swagger UI configuration example
    openapi({
      provider: 'swagger-ui',
      swagger: {
        theme: { light: 'css-string', dark: 'css-string' },
        autoDarkMode: true
      }
    })
  10. Generate Swagger UI HTML with SwaggerUIRender

    main

    The SwaggerUIRender function generates a complete HTML string to serve a Swagger UI documentation page. It takes OpenAPI information and configuration options to customize the look and feel of the documentation.

    Configuration Options

    When calling SwaggerUIRender, you can provide the following configuration via the config object:

    • version (string, default: 'latest'): The version of swagger-ui-dist to use from the Unpkg CDN.
    • theme (string | { light: string, dark: string }):
      • If a string, it is used as the CSS stylesheet URL.
      • If an object with light and dark keys, it provides specific stylesheets for different color schemes.
    • cdn (string, default: uses version to build a URL): The URL for the swagger-ui-bundle.js script.
    • autoDarkMode (boolean, default: true): If true, injects CSS to automatically apply a dark mode filter to the Swagger UI based on the user's system preference.
    • ...rest: Any other valid SwaggerUIOptions (passed directly to the SwaggerUIBundle constructor).

    Note: Functions passed in the configuration object are automatically stripped out before being stringified for the browser-side script.

    import { SwaggerUIRender } from './src/swagger/index'
    import { OpenAPIV3 } from 'openapi-types'
    
    const info: OpenAPIV3.InfoObject = {
        title: 'My API',
        version: '1.0.0',
        description: 'An example API'
    }
    
    const config = {
        version: '5.17.11',
        autoDarkMode: true,
        // other SwaggerUIOptions
    }
    
    const html = SwaggerUIRender(info, config)
  11. Use ScalarRender to generate Scalar documentation HTML

    main

    The ScalarRender function generates a complete HTML string used to serve the Scalar API documentation UI. It takes the OpenAPI information object, a configuration object, and an optional embedded specification string.

    This function is typically used internally by @elysia/openapi to provide a visual interface for your API documentation. It injects the provided configuration and any custom CSS into a standalone HTML document that loads the Scalar library via the specified CDN.

    import { ScalarRender } from './src/scalar/index'
    import type { OpenAPIV3 } from 'openapi-types'
    
    // Example usage (internal/manual implementation)
    const html = ScalarRender(
      { title: 'My API', description: 'An example API' } as OpenAPIV3.InfoObject,
      { 
        cdn: 'https://cdn.jsdelivr.net/npm/@scalar/api-reference', 
        customCss: '.my-class { color: red; }' 
      },
      '{"openapi": "3.0.0", ...}' // embedSpec
    );