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-project
Then, initialize tsconfig.json
:
tsc --init
Now, initialize package.json
and install tspec:
yarn init -y
yarn add tspec
npm init -y
npm install tspec
pnpm init -y
pnpm add tspec
Define 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.json
npx tspec generate --outputPath openapi.json
pnpm tspec generate --outputPath openapi.json
Generated 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
- title
TIP
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 3000
npx tspec server --port 3000
pnpm tspec server --port 3000
Then, 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.