Getting Started
On this page, we will learn how to use tspec to generate OpenAPI Specification from TypeScript types and serve it with Swagger UI.
Installing
Assuming you have Node.js and TypeScript installed, create a new typescript project:
mkdir my-project
cd my-projectThen, initialize tsconfig.json:
tsc --initNow, initialize package.json and install tspec:
yarn init -y
yarn add tspecnpm init -y
npm install tspecpnpm init -y
pnpm add tspecDefine ApiSpec
Let's define a simple Book type and BookApiSpec:
import { Tspec } from "tspec";
/** Schema description defined by JSDoc */
interface Book {
/** Field description defined by JSDoc */
id: number;
title: string;
description?: string;
}
export type BookApiSpec = Tspec.DefineApiSpec<{
paths: {
'/books/{id}': {
get: {
summary: 'Get book by id',
path: { id: number },
responses: { 200: Book },
},
},
}
}>;Generate OpenAPI Spec
Now, let's generate OpenAPI Spec from BookApiSpec:
yarn tspec generate --outputPath openapi.jsonnpx tspec generate --outputPath openapi.jsonpnpm tspec generate --outputPath openapi.jsonGenerated OpenAPI Spec
(For readability, the generated OpenAPI Spec is formatted with yaml)
openapi: 3.0.3
info:
title: Tspec API
version: 0.0.1
paths:
/books/{id}:
get:
operationId: BookApiSpec_get_/books/{id}
tags:
- Book
summary: Get book by id
parameters:
- name: id
in: path
required: true
schema:
type: number
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/Book'
components:
schemas:
Book:
description: Schema description defined by JSDoc
type: object
properties:
id:
description: Field description defined by JSDoc
type: number
title:
type: string
description:
type: string
required:
- id
- titleTIP
Tspec automatically parses ApiSpec from any files that match the glob pattern **/*.ts in the current working directory.
If you want to specify a different spec path, you can use the --specPathGlobs option.
Serve OpenAPI Spec
Now, let's serve the OpenAPI Spec with Swagger UI:
yarn tspec server --port 3000npx tspec server --port 3000pnpm tspec server --port 3000Then, open http://localhost:3000/docs in your browser.
You will see the Swagger UI page:

And you can see schema definitions in the Schemas tab.
