Spoosh
Integrations

OpenAPI

Generate OpenAPI 3.0 specs from your TypeScript schema

The @spoosh/openapi package generates OpenAPI 3.0 specifications from your TypeScript API schema types.

Installation

npm install @spoosh/openapi

CLI Usage

# Generate OpenAPI spec from schema
npx spoosh-openapi -s ./src/schema.ts -o openapi.json

# With custom options
npx spoosh-openapi \
  --schema ./src/api-schema.ts \
  --type MyApiSchema \
  --output ./docs/openapi.json \
  --title "My API" \
  --version "2.0.0" \
  --base-url "https://api.example.com"

Schema File

src/schema.ts
import type { Endpoint, EndpointWithQuery } from "@spoosh/core";

interface User {
  id: number;
  name: string;
  email: string;
}

interface CreateUserBody {
  name: string;
  email: string;
}

export type ApiSchema = {
  users: {
    $get: EndpointWithQuery<User[], { page?: number; limit?: number }>;
    $post: Endpoint<User, CreateUserBody>;
    _: {
      $get: Endpoint<User>;
      $put: Endpoint<User, Partial<CreateUserBody>>;
      $delete: void;
    };
  };
  health: {
    $get: { status: string };
  };
};

Generated Output

{
  "openapi": "3.0.0",
  "info": {
    "title": "My API",
    "version": "2.0.0"
  },
  "servers": [{ "url": "https://api.example.com" }],
  "paths": {
    "/users": {
      "get": {
        "parameters": [
          { "name": "page", "in": "query", "schema": { "type": "number" } },
          { "name": "limit", "in": "query", "schema": { "type": "number" } }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": { "$ref": "#/components/schemas/User" }
                }
              }
            }
          }
        }
      }
    }
  }
}

CLI Options

OptionAliasRequiredDefaultDescription
--schema-sYes-Path to TypeScript file containing schema
--type-tNoApiSchemaName of the schema type to use
--output-oNostdoutOutput file path
--title-No-API title for OpenAPI info
--version-No1.0.0API version for OpenAPI info
--base-url-No-Base URL for servers array

Programmatic Usage

import { parseSchema, generateOpenAPISpec } from "@spoosh/openapi";

const { endpoints, schemas } = parseSchema("./src/schema.ts", "ApiSchema");

const spec = generateOpenAPISpec(endpoints, schemas, {
  title: "My API",
  version: "1.0.0",
  baseUrl: "https://api.example.com",
});

console.log(JSON.stringify(spec, null, 2));

On this page