Adrian Moisa
Adrian Moisa

Reputation: 4363

Generating swagger docs from typescript interfaces

I'm using swager-jsdoc to document all the DTOs of the app.

I was wondering is there any way to generate the swagger docs automatically from typescript interfaces.

I have a lot of them in the project and also a lot of mongoose schemas and models. It is getting tedious to keep them in sync. On the other hand I do not want to use the swagger generation tools. I prefer the bottom-up approach.

Cheers

Upvotes: 23

Views: 24485

Answers (3)

GreeneCreations
GreeneCreations

Reputation: 1242

Yes, you can easily generate Swagger and OpenAPI documents from your TypeScript types by using tsoa. The readme contains all of the setup information that you would need to start using it. It's compatible with express, hapi, koa, and more:

https://github.com/lukeautry/tsoa


(Full Transparency: I ~am~ was one of the maintainers of tsoa. But I was first a consumer of tsoa and I find it to be a great product... that's why I asked to help maintain it! :) ) I’ve since stepped back, but the new maintainers are awesome!

Upvotes: 7

Aleksi
Aleksi

Reputation: 5046

Another option to tsoa is routing-controllers + routing-controllers-openapi. The main difference between the two (AFAIK) is that tsoa relies on code generation whereas routing-controllers operates wholly on runtime. Both methods have their upsides: tsoa is able to e.g. utilize richer metadata (such as code comments) whereas with routing-controllers we can skip the generation step. My recommendation is to check both out!

One more option is typescript-json-schema, which generates JSON Schema out of Typescript interfaces; after you have defined your models in JSON Schema you're not terribly far off from an OpenAPI spec.

Upvotes: 8

Ricardo Emerson
Ricardo Emerson

Reputation: 906

Another option is use https://www.npmjs.com/package/ts-to-openapi to generate Swagger Schemas From the interfaces.

Example: Considering the User interface bellow:

export interface User {
  name: string;
  email: string;
  nickname?: string;
}

In terminal run the followed command:

npx ts-to-openapi -f User.ts -t User >> User.ts

After this your interface User will be updates as bellow:

export interface User {
  name: string;
  email: string;
  nickname?: string;
}

/**
 * @swagger
 * components:
 *   schemas:
 *     User:
 *       additionalProperties: false
 *       properties:
 *         email:
 *           type: string
 *         name:
 *           type: string
 *         nickname:
 *           type: string
 *       required:
 *         - name
 *         - email
 *       type: object
 */

Upvotes: 2

Related Questions