Swagger: Use example

Created on 11 Oct 2017  路  12Comments  路  Source: nestjs/swagger

Hi,all

Can some one provide some use example? plz ;)

Most helpful comment

I'm using it that way, I do not know if it's the right way, but it works.

in server.ts
I tell him to generate the json with the methods.

const instance = express();
/* Express middleware. */
instance.use(bodyParser.json());
instance.use(bodyParser.urlencoded({ extended: false }));
instance.use(cors());
/* End of express middleware. */

async function bootstrap() {
  try {
    const app = await NestFactory.create(ApplicationModule, instance);
    app.useGlobalFilters(new DispatchError());
    await app.listen(Config.number("HTTP_PORT", 9090), Config.string("LISTEN_INTERFACE", "0.0.0.0"), () => console.log('Application is listening on port ' + Config.number("HTTP_PORT", 9090)));

    instance.get('/api-docs.json', function (req, res) {
      res.setHeader('Content-Type', 'application/json');
      res.send(SwaggerModule.createDocument(app,
        {
          info: {
            title: "My App", description: "My App Description",
            contact: { email: "[email protected]" }
          },
          securityDefinitions: { bearer: { type: "apiKey", name: "Authorization", in: "header" } }
        }));
    });
  } catch (e) { }
}
bootstrap();

in controller

    @ApiOperation({ description: "Disable Company", operationId: "disable", title: "Disable Company" })
    @ApiImplicitBody({ name: "company", required: true, type: CompanyId })
    @ApiResponse({ status: 400, description: "Missing info: compId" })
    @ApiResponse({ status: 200, description: "disable OK", type: Company })
    @Post("disable")
    public async disable( @Req() req, @Res() res: Response) {

    }

```javascript
instead of @ApiImplicitBody(), you can use @Body() as parameter in function

```javascript
//in Body Type. @ApiModelProperty()
export class CompanyId {
    @ApiModelProperty()
    compId: number;
}

all decorators are in

import { APIXX } from '@nestjs/swagger';

http://localhost:8080/api-docs.json (assuming 8080 is the port of your app )
this url I place it in swagger-ui and it already shows the information of the api.
http://petstore.swagger.io/ (you can try localhost url)

All 12 comments

I'm using it that way, I do not know if it's the right way, but it works.

in server.ts
I tell him to generate the json with the methods.

const instance = express();
/* Express middleware. */
instance.use(bodyParser.json());
instance.use(bodyParser.urlencoded({ extended: false }));
instance.use(cors());
/* End of express middleware. */

async function bootstrap() {
  try {
    const app = await NestFactory.create(ApplicationModule, instance);
    app.useGlobalFilters(new DispatchError());
    await app.listen(Config.number("HTTP_PORT", 9090), Config.string("LISTEN_INTERFACE", "0.0.0.0"), () => console.log('Application is listening on port ' + Config.number("HTTP_PORT", 9090)));

    instance.get('/api-docs.json', function (req, res) {
      res.setHeader('Content-Type', 'application/json');
      res.send(SwaggerModule.createDocument(app,
        {
          info: {
            title: "My App", description: "My App Description",
            contact: { email: "[email protected]" }
          },
          securityDefinitions: { bearer: { type: "apiKey", name: "Authorization", in: "header" } }
        }));
    });
  } catch (e) { }
}
bootstrap();

in controller

    @ApiOperation({ description: "Disable Company", operationId: "disable", title: "Disable Company" })
    @ApiImplicitBody({ name: "company", required: true, type: CompanyId })
    @ApiResponse({ status: 400, description: "Missing info: compId" })
    @ApiResponse({ status: 200, description: "disable OK", type: Company })
    @Post("disable")
    public async disable( @Req() req, @Res() res: Response) {

    }

```javascript
instead of @ApiImplicitBody(), you can use @Body() as parameter in function

```javascript
//in Body Type. @ApiModelProperty()
export class CompanyId {
    @ApiModelProperty()
    compId: number;
}

all decorators are in

import { APIXX } from '@nestjs/swagger';

http://localhost:8080/api-docs.json (assuming 8080 is the port of your app )
this url I place it in swagger-ui and it already shows the information of the api.
http://petstore.swagger.io/ (you can try localhost url)

You can also use 'swagger-ui-express':

  const documentBuilder = new DocumentBuilder();
  documentBuilder.addBearerAuth('Authorization', 'header');
  const document = SwaggerModule.createDocument(nestApp, documentBuilder.build());
  expressApp.use('/swagger', swaggerUI.serve, swaggerUI.setup(document));
  expressApp.use('/api-docs', (req, res, next) => res.send(document));

I tried this but i get TypeError: Cannot read property 'path' of undefined when starting the server.

can you put your server.ts? and the controller where are you using them?

server.ts

    await app.listen(port);
    const config = new DocumentBuilder().addBearerAuth().build();
    const document = SwaggerModule.createDocument(app, config);
    instance.get('/api-docs.json', (req, res) => {
        res.setHeader('Content-Type', 'application/json');
        res.send(SwaggerModule.createDocument(app, document));
    });
@ApiOperation({ title: 'Get all' })
@ApiResponse({ status: 200, description: 'Items', type: XXX })
@Get()
public async getAll( @Req() req):

you are creating the document twice. SwaggerModule.createDocument

const document = SwaggerModule.createDocument (app, config);

res.send (SwaggerModule.createDocument (app, document));

Good point (copy-paste daah). I changed res.send(document); but i still same issue. The problem seems to be SwaggerModule.createDocument(app, config) . I don't need to use any decorators to get that error. Also documentBuilder.setBasePath does not have any effect.

And if anyone else is wondering, you can import SwaggerModule with import { SwaggerModule } from "@nestjs/swagger";

Here's an example https://docs.nestjs.com/recipes/swagger 馃檪

A real world example can also be found here : https://github.com/nartc/nest-mean

Nest + sequelize-typescript + JWT + Jest + Swagger
https://github.com/kentloog/nestjs-sequelize-typescript

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

KatSick picture KatSick  路  3Comments

Fiorello picture Fiorello  路  5Comments

ericzon picture ericzon  路  4Comments

alisherks picture alisherks  路  4Comments

djedlajn picture djedlajn  路  4Comments