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

openapi30-builder.mddocs/

OpenAPI 3.0 Builder

Fluent DSL for creating OpenAPI 3.0 specification documents with complete type safety and chainable operations.

Capabilities

OpenApiBuilder Class

Main builder class for constructing OpenAPI 3.0 documents through a fluent interface.

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

Document Access Methods

Methods for retrieving and serializing the OpenAPI document.

/**
 * Get the current OpenAPI document
 * @returns The OpenAPI document object
 */
getSpec(): oas30.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

Methods for setting basic document information. All methods return OpenApiBuilder for chaining.

/**
 * Set the OpenAPI version
 * @param openApiVersion - OpenAPI version string (e.g., "3.0.3")
 * @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: oas30.InfoObject): OpenApiBuilder;

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

/**
 * Set license information
 * @param license - License object with name and optional url
 * @returns Builder instance for chaining
 */
addLicense(license: oas30.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

Methods for defining API paths and operations.

/**
 * Add or merge a path item
 * @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: oas30.PathItemObject): OpenApiBuilder;

Usage Example:

builder.addPath("/pets", {
  get: {
    summary: "List all pets",
    responses: {
      "200": {
        description: "A list of pets",
        content: {
          "application/json": {
            schema: {
              type: "array",
              items: { $ref: "#/components/schemas/Pet" }
            }
          }
        }
      }
    }
  },
  post: {
    summary: "Create a pet",
    requestBody: {
      required: true,
      content: {
        "application/json": {
          schema: { $ref: "#/components/schemas/Pet" }
        }
      }
    },
    responses: {
      "201": {
        description: "Pet created successfully",
        content: {
          "application/json": {
            schema: { $ref: "#/components/schemas/Pet" }
          }
        }
      }
    }
  }
});

Component Methods

Methods for adding reusable components. All methods return OpenApiBuilder for chaining.

/**
 * Add a schema component
 * @param name - Schema name for referencing
 * @param schema - Schema object or reference
 * @returns Builder instance for chaining
 */
addSchema(name: string, schema: oas30.SchemaObject | oas30.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: oas30.ResponseObject | oas30.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: oas30.ParameterObject | oas30.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: oas30.ExampleObject | oas30.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: oas30.RequestBodyObject | oas30.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: oas30.HeaderObject | oas30.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: oas30.SecuritySchemeObject | oas30.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: oas30.LinkObject | oas30.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: oas30.CallbackObject | oas30.ReferenceObject): OpenApiBuilder;

Usage Example:

builder
  .addSchema("Pet", {
    type: "object",
    required: ["id", "name"],
    properties: {
      id: { type: "integer", format: "int64" },
      name: { type: "string" },
      tag: { type: "string" }
    }
  })
  .addResponse("NotFound", {
    description: "The specified resource was not found",
    content: {
      "application/json": {
        schema: {
          type: "object",
          properties: {
            error: { type: "string" },
            code: { type: "integer" }
          }
        }
      }
    }
  });

Server and Tag Methods

Methods for adding servers and tags.

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

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

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

Usage Example:

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

const server = new Server("https://api.example.com/v1", "Production server");
server.addVariable("version", new ServerVariable("v1", ["v1", "v2"], "API version"));

builder
  .addServer(server)
  .addTag({
    name: "pets",
    description: "Operations about pets"
  })
  .addExternalDocs({
    description: "Find more info here",
    url: "https://example.com/docs"
  });

Complete Example

import { oas30, Server, ServerVariable } from "openapi3-ts";

const spec = oas30.OpenApiBuilder.create()
  .addOpenApiVersion("3.0.3")
  .addTitle("Pet Store API")
  .addVersion("1.0.0")
  .addDescription("A sample API that uses a petstore as an example")
  .addContact({
    name: "Swagger API Team",
    email: "apiteam@swagger.io",
    url: "http://swagger.io"
  })
  .addLicense({
    name: "MIT",
    url: "https://opensource.org/licenses/MIT"
  })
  .addServer(new Server("https://petstore.swagger.io/v2", "Swagger Petstore"))
  .addTag({
    name: "pet",
    description: "Everything about your Pets"
  })
  .addSchema("Pet", {
    type: "object",
    required: ["name", "photoUrls"],
    properties: {
      id: { type: "integer", format: "int64" },
      name: { type: "string", example: "doggie" },
      photoUrls: {
        type: "array",
        items: { type: "string" }
      },
      status: {
        type: "string",
        enum: ["available", "pending", "sold"]
      }
    }
  })
  .addPath("/pet", {
    post: {
      tags: ["pet"],
      summary: "Add a new pet to the store",
      requestBody: {
        description: "Pet object that needs to be added to the store",
        required: true,
        content: {
          "application/json": {
            schema: { $ref: "#/components/schemas/Pet" }
          }
        }
      },
      responses: {
        "405": {
          description: "Invalid input"
        }
      }
    }
  })
  .getSpec();

// Export to different formats
const json = oas30.OpenApiBuilder.create(spec).getSpecAsJson(null, 2);
const yaml = oas30.OpenApiBuilder.create(spec).getSpecAsYaml();

// Export YAML with custom options
const customYaml = oas30.OpenApiBuilder.create(spec).getSpecAsYaml(
  null, // replacer function (can filter/transform values)
  {
    indent: 4,        // Use 4-space indentation instead of default 2
    lineWidth: 120,   // Longer line width
    flowLevel: 2      // Use flow style for deeply nested objects
  }
);

console.log("Default YAML:", yaml);
console.log("Custom formatted YAML:", 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