CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-openapi3-ts

TypeScript models and utilities for building OpenAPI 3.x specification documents with fluent DSL builder pattern

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

openapi31-builder.mddocs/

OpenAPI 3.1 Builder

Fluent DSL for creating OpenAPI 3.1 specification documents with enhanced JSON Schema support and webhook capabilities.

Capabilities

OpenApiBuilder Class

Main builder class for constructing OpenAPI 3.1 documents through a fluent interface. Inherits all OpenAPI 3.0 capabilities with 3.1-specific enhancements.

/**
 * Internal DSL for building an OpenAPI 3.1.x contract using a fluent interface
 */
class OpenApiBuilder {
  rootDoc: oas31.OpenAPIObject;
  
  /**
   * Factory method to create a new builder instance
   * @param doc - Optional initial OpenAPI document
   * @returns New OpenApiBuilder instance
   */
  static create(doc?: oas31.OpenAPIObject): OpenApiBuilder;
  
  /**
   * Constructor for OpenApiBuilder
   * @param doc - Optional initial OpenAPI document, defaults to minimal 3.1 structure
   */
  constructor(doc?: oas31.OpenAPIObject);
}

Document Access Methods

Same as OpenAPI 3.0 with OpenAPI 3.1 document support.

/**
 * Get the current OpenAPI 3.1 document
 * @returns The OpenAPI 3.1 document object
 */
getSpec(): oas31.OpenAPIObject;

/**
 * Serialize the OpenAPI document to JSON string
 * @param replacer - JSON.stringify replacer function
 * @param space - Indentation for pretty printing
 * @returns JSON string representation
 */
getSpecAsJson(
  replacer?: (key: string, value: unknown) => unknown,
  space?: string | number
): string;

/**
 * Serialize the OpenAPI document to YAML string
 * @param replacer - YAML stringify replacer
 * @param options - YAML stringify options
 * @returns YAML string representation
 */
getSpecAsYaml(
  replacer?: Parameters<typeof yaml.stringify>[1],
  options?: Parameters<typeof yaml.stringify>[2]
): string;

Document Metadata Methods

All OpenAPI 3.0 metadata methods are available with OpenAPI 3.1 type support. All methods return OpenApiBuilder for chaining.

/**
 * Set the OpenAPI version (defaults to 3.1.0)
 * @param openApiVersion - OpenAPI version string (e.g., "3.1.0")
 * @returns Builder instance for chaining
 * @throws Error if version format is invalid
 */
addOpenApiVersion(openApiVersion: string): OpenApiBuilder;

/**
 * Set the info object
 * @param info - Complete info object
 * @returns Builder instance for chaining
 */
addInfo(info: oas31.InfoObject): OpenApiBuilder;

/**
 * Set contact information
 * @param contact - Contact object with name, url, email
 * @returns Builder instance for chaining
 */
addContact(contact: oas31.ContactObject): OpenApiBuilder;

/**
 * Set license information (with optional identifier field for OpenAPI 3.1)
 * @param license - License object with name, optional url and identifier
 * @returns Builder instance for chaining
 */
addLicense(license: oas31.LicenseObject): OpenApiBuilder;

/**
 * Set API title
 * @param title - API title string
 * @returns Builder instance for chaining
 */
addTitle(title: string): OpenApiBuilder;

/**
 * Set API description
 * @param description - API description string
 * @returns Builder instance for chaining
 */
addDescription(description: string): OpenApiBuilder;

/**
 * Set terms of service URL
 * @param termsOfService - Terms of service URL
 * @returns Builder instance for chaining
 */
addTermsOfService(termsOfService: string): OpenApiBuilder;

/**
 * Set API version
 * @param version - API version string
 * @returns Builder instance for chaining
 */
addVersion(version: string): OpenApiBuilder;

Path and Operation Methods

Enhanced path support with optional paths object in OpenAPI 3.1.

/**
 * Add or merge a path item (paths object is optional in OpenAPI 3.1)
 * @param path - URL path string (e.g., "/pets/{id}")
 * @param pathItem - Path item object with operations
 * @returns Builder instance for chaining
 */
addPath(path: string, pathItem: oas31.PathItemObject): OpenApiBuilder;

Webhook Methods (OpenAPI 3.1 Specific)

OpenAPI 3.1 introduces webhook support for defining callback operations initiated by the API provider.

/**
 * Add a webhook definition (OpenAPI 3.1 feature)
 * @param webhook - Webhook name/key
 * @param webhookItem - Path item describing the webhook callback
 * @returns Builder instance for chaining
 */
addWebhook(webhook: string, webhookItem: oas31.PathItemObject): OpenApiBuilder;

Usage Example:

builder.addWebhook("petUpdated", {
  post: {
    summary: "Pet updated webhook",
    description: "Called when a pet is updated in the system",
    requestBody: {
      description: "Updated pet information",
      content: {
        "application/json": {
          schema: { $ref: "#/components/schemas/Pet" }
        }
      }
    },
    responses: {
      "200": {
        description: "Webhook successfully processed"
      }
    }
  }
});

Component Methods

All OpenAPI 3.0 component methods with OpenAPI 3.1 type support and enhanced components.

/**
 * Add a schema component (with enhanced OpenAPI 3.1 JSON Schema support)
 * @param name - Schema name for referencing
 * @param schema - Schema object or reference
 * @returns Builder instance for chaining
 */
addSchema(name: string, schema: oas31.SchemaObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add a response component
 * @param name - Response name for referencing
 * @param response - Response object or reference
 * @returns Builder instance for chaining
 */
addResponse(name: string, response: oas31.ResponseObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add a parameter component
 * @param name - Parameter name for referencing
 * @param parameter - Parameter object or reference
 * @returns Builder instance for chaining
 */
addParameter(name: string, parameter: oas31.ParameterObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add an example component
 * @param name - Example name for referencing
 * @param example - Example object or reference
 * @returns Builder instance for chaining
 */
addExample(name: string, example: oas31.ExampleObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add a request body component
 * @param name - Request body name for referencing
 * @param reqBody - Request body object or reference
 * @returns Builder instance for chaining
 */
addRequestBody(name: string, reqBody: oas31.RequestBodyObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add a header component
 * @param name - Header name for referencing
 * @param header - Header object or reference
 * @returns Builder instance for chaining
 */
addHeader(name: string, header: oas31.HeaderObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add a security scheme component
 * @param name - Security scheme name for referencing
 * @param secScheme - Security scheme object or reference
 * @returns Builder instance for chaining
 */
addSecurityScheme(name: string, secScheme: oas31.SecuritySchemeObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add a link component
 * @param name - Link name for referencing
 * @param link - Link object or reference
 * @returns Builder instance for chaining
 */
addLink(name: string, link: oas31.LinkObject | oas31.ReferenceObject): OpenApiBuilder;

/**
 * Add a callback component
 * @param name - Callback name for referencing
 * @param callback - Callback object or reference
 * @returns Builder instance for chaining
 */
addCallback(name: string, callback: oas31.CallbackObject | oas31.ReferenceObject): OpenApiBuilder;

Server and Tag Methods

Same as OpenAPI 3.0 with OpenAPI 3.1 type support.

/**  
 * Add a server to the document
 * @param server - Server object with URL and description
 * @returns Builder instance for chaining
 */
addServer(server: oas31.ServerObject): OpenApiBuilder;

/**
 * Add a tag to the document
 * @param tag - Tag object with name and description
 * @returns Builder instance for chaining
 */
addTag(tag: oas31.TagObject): OpenApiBuilder;

/**
 * Set external documentation
 * @param extDoc - External documentation object
 * @returns Builder instance for chaining
 */
addExternalDocs(extDoc: oas31.ExternalDocumentationObject): OpenApiBuilder;

OpenAPI 3.1 Enhanced Features

Enhanced JSON Schema Support

OpenAPI 3.1 schemas support JSON Schema Draft 2020-12 features:

builder.addSchema("EnhancedPet", {
  type: "object",
  required: ["name"],
  properties: {
    name: { type: "string" },
    age: { 
      type: "integer",
      minimum: 0,
      exclusiveMinimum: 0, // Numeric value in 3.1 (vs boolean in 3.0)
      maximum: 30,
      exclusiveMaximum: 30 // Numeric value in 3.1 (vs boolean in 3.0)
    },
    type: {
      const: "pet" // const keyword support
    },
    tags: {
      type: "array",
      prefixItems: [ // Tuple validation support
        { type: "string" },
        { type: "string" }
      ],
      items: false // No additional items allowed
    },
    metadata: {
      type: "string",
      contentMediaType: "application/json", // Content media type
      contentEncoding: "base64" // Content encoding
    }
  },
  propertyNames: { // Property name constraints
    pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$"
  }
});

Enhanced Reference Objects

OpenAPI 3.1 reference objects support summary and description:

builder.addSchema("PetReference", {
  $ref: "#/components/schemas/Pet",
  summary: "Pet model reference",
  description: "Reference to the main Pet schema with additional context"
});

Complete OpenAPI 3.1 Example

import { oas31, Server } from "openapi3-ts";

const spec = oas31.OpenApiBuilder.create()
  .addOpenApiVersion("3.1.0")
  .addTitle("Advanced Pet Store API")
  .addVersion("2.0.0")
  .addDescription("An enhanced API with OpenAPI 3.1 features")
  .addLicense({
    name: "MIT",
    identifier: "MIT", // OpenAPI 3.1 license identifier
    url: "https://opensource.org/licenses/MIT"
  })
  .addServer(new Server("https://api.petstore.com", "Production server"))
  .addSchema("Pet", {
    type: "object",
    required: ["name"],
    properties: {
      id: { type: "integer", format: "int64" },
      name: { type: "string" },
      status: {
        type: "string",
        enum: ["available", "pending", "sold"]
      },
      category: {
        type: "object",
        properties: {
          id: { type: "integer" },
          name: { 
            type: "string",
            const: "pet-category" // OpenAPI 3.1 const support
          }
        }
      },
      metadata: {
        type: "string",
        contentMediaType: "application/json",
        contentEncoding: "base64"
      }
    },
    propertyNames: {
      pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$"
    }
  })
  .addPath("/pets", {
    get: {
      summary: "List pets",
      responses: {
        "200": {
          description: "Successful response",
          content: {
            "application/json": {
              schema: {
                type: "array",
                items: { $ref: "#/components/schemas/Pet" }
              }
            }
          }
        }
      }
    }
  })
  .addWebhook("petStatusChanged", {
    post: {
      summary: "Pet status changed webhook",
      requestBody: {
        content: {
          "application/json": {
            schema: { $ref: "#/components/schemas/Pet" }
          }
        }
      },
      responses: {
        "200": {
          description: "Webhook processed successfully"
        }
      }
    }
  })
  .getSpec();

// Export to different formats with enhanced OpenAPI 3.1 features
const json = builder.getSpecAsJson(null, 2);
const yaml = builder.getSpecAsYaml();

// Export YAML with custom formatting for OpenAPI 3.1
const customYaml = builder.getSpecAsYaml(
  null, // replacer function 
  {
    indent: 4,        // 4-space indentation
    lineWidth: 100,   // Wrap long lines
    flowLevel: 3,     // Use flow style for deep nesting
    sortKeys: true    // Sort object keys alphabetically
  }
);

console.log("OpenAPI 3.1 YAML:", yaml);
console.log("Custom formatted:", customYaml);

Install with Tessl CLI

npx tessl i tessl/npm-openapi3-ts

docs

index.md

openapi30-builder.md

openapi30-types.md

openapi31-builder.md

openapi31-types.md

server-management.md

specification-extensions.md

tile.json