Generating OpenAPI Specs using Typescript and Express
Working on a backend app right now, and needed to document the endpoints, and also didn't want to spend the time writing it from scratch.
Used tspec to integrate with the code, picked up the types from the controller and just had to define the resposnes and the types along with it.
Steps to use tspec1
- Instal tspec
$ pnpm i tspec
- Define a Spec
import { Tspec } from 'tspec';
/** Schema description defined by JSDoc */
interface User {
/** Field description defined by JSDoc */
id: number;
fullName: string;
username: string;
}
export type UserApiSpec = Tspec.DefineApiSpec<{
paths: {
'/users/{id}': {
get: {
summary: 'Get user by id';
path: { id: number };
responses: { 200: User };
};
};
};
}>;
- Generate the OpenAPI Specs
$ npx tspec generate --outputPath openapi.json
Other References
- If you're looking for related tools to OpenAPI, check this out - https://openapi.tools/
- Write a scalable OpenAPI specification for a Node.js API
For other options, view the documentation of tspec2.