GithubHelp home page GithubHelp logo

Swagger integration about nest HOT 29 CLOSED

nestjs avatar nestjs commented on April 24, 2024 12
Swagger integration

from nest.

Comments (29)

kamilmysliwiec avatar kamilmysliwiec commented on April 24, 2024 24

There's a repository https://github.com/nestjs/swagger
Package is published as @nestjs/swagger
I'm creating the tutorial now

from nest.

kamilmysliwiec avatar kamilmysliwiec commented on April 24, 2024 19

Hi @Martodox,
Definitely needed! I'll make it in the future. Stay tuned 😄

from nest.

Jorgevillada avatar Jorgevillada commented on April 24, 2024 11

could you share the progress of the swagger documentation and tell us how we can help you?

from nest.

kamilmysliwiec avatar kamilmysliwiec commented on April 24, 2024 7

Hi guys,
Swagger module is in beta stage. Hope to share it with you asap 😃

from nest.

kamilmysliwiec avatar kamilmysliwiec commented on April 24, 2024 5

Here's an example https://docs.nestjs.com/recipes/swagger 🙂 I hope it's enough for now!

from nest.

kamilmysliwiec avatar kamilmysliwiec commented on April 24, 2024 3

@qinyang1980 one time 😄
@LuukMoret in progress 💪

from nest.

cojack avatar cojack commented on April 24, 2024 1

@Martodox hmm if there will be an solution to inject some "middleware" into http controllers, there will be option to create independent module for nest to generate a swagger.json file as output ;>

@kamilmysliwiec an extra events like hooks ;) hmmm ;>

from nest.

darioxtx avatar darioxtx commented on April 24, 2024 1

Hi,

here is example of basic usage:

@Controller('status')
@ApiUseTags("status") // OpenAPI tag property
export class StatusController {

    @Get("/status")
    @ApiOperation({title: "Returns API status"})
    @ApiResponse({status: HttpStatus.OK, type: StatusModel, description: "Returns API status"})
    @ApiResponse({status: "default", type: RequestException, description: "Error Response"})
    async getStatus(@Req() req, @Res() res) {
        return await this.statusService.getStatus();
    }
}

//model definition
export class StatusModel {

    @ApiModelProperty()
    public status: string;

    @ApiModelProperty()
    public uptime: Date;

    @ApiModelProperty({items: {type: 'string', enum: SomeEnum}})
    public items: SomeEnum[];
}

export class RequestException {

    @ApiModelProperty()
    private readonly message: string;
    @ApiModelProperty()
    private readonly status: number;

    constructor(message: string, status: number) {
        this.message = message;
        this.status = status
    }

    getMessage(): string {
        return this.message;
    }

    getStatus(): number {
        return this.status;
    }
}

//server.ts
async function bootstrap() {
    const express = require("express");
    const swaggerUi = require('swagger-ui-express');
    const server = express();
    const app = await NestFactory.create(ApplicationModule, server);

    let apiDoc = SwaggerModule.createDocument(app, {
        //TODO: swagger: '2.0',
        info: {
            description: "OpenAPI",
            version: "1.0.0",
            title: "OpenAPI",
        },
        basePath: "/api"
    });
    apiDoc['swagger'] = '2.0';

    server.get('/api-docs/swagger.json', function (req, res) { //swagger json
        res.json(apiDoc);
    });
    server.use('/api-docs/ui', swaggerUi.serve, swaggerUi.setup(apiDoc)); //swagger ui
    // SwaggerModule.setup('/api-docs/ui', app, apiDoc); //not working
}
bootstrap();

Hope it helps to start

from nest.

Jorgevillada avatar Jorgevillada commented on April 24, 2024 1

You can also see an example here. nestjs/swagger#4

from nest.

MaheshCasiraghi avatar MaheshCasiraghi commented on April 24, 2024 1

Cool @darioxtx, thank you. I ended up following a separate solution, based on the thread @Jorgevillada proposed, with some due modifications. Here my server.ts, it creates a http://localhost:3001/swagger ui which interacts with the nest app at localhost 3000:

import * as bodyParser from 'body-parser';
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './modules/app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

const express = require('express');
const cors = require('cors');
const swaggerUI = require('swagger-ui-express');

const showExplorer = true;
const appHost = 'localhost:3000';
async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  const Eapp = express();

  Eapp.use(cors());
  app.use(cors());
  app.use(bodyParser.json());

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

  await Eapp.listen(3001);
  await app.listen(3000);
}

bootstrap();

from nest.

marcelfalliere avatar marcelfalliere commented on April 24, 2024 1

Amazing thread :)

quick question : how do you generate a static website of the documentation ? So far, it's only available when running the nest server. I don't wish to expose the swagger to everyone when starting the server.

from nest.

Martodox avatar Martodox commented on April 24, 2024

@kamilmysliwiec The project that I had started at work copied my approach from my another project: sample file with swagger-jsdoc. It does the job, but it would be cool to integrate it with TS decorators (just like java swing).

from nest.

KatSick avatar KatSick commented on April 24, 2024

@kamilmysliwiec any updates on swagger module ? maybe i can help at least in testing ?

from nest.

irissoftworks avatar irissoftworks commented on April 24, 2024

Hey guys. I have to say that Nest looks really good. Kudos to the dev team.

Good architecture, and learning curve is minimal if Angular is your background.
Not having swagger integration is a major issue though (pretty much the only issue I found so far).
Everyone who's got Angular skills will want to generate their client code and use swagger tooling.

Maintaining a swagger spec in sync manually is a nightmare, so if this issue could be fixed, then Nest ( combined with typeorm ) would probably be the ultimate way to go on the node side of things.
I am currently using TSOA which provides a swagger spec from the route decorators and it's fairly mature.

Decorators aren't too different from the ones on Nest. I didn't investigate how much of that code would be portable ?

Anyway, let me know if there's anything I can do to speed this up, as the above poster said, even if it's just testing.

from nest.

ericzon avatar ericzon commented on April 24, 2024

@irissoftworks I think Swagger integration is ready on release/v4 branch. I hope it would be ready soon to start playing with.

from nest.

irissoftworks avatar irissoftworks commented on April 24, 2024

Great! Apologies everyone, I went through the other branch yesterday, but I think I must have missed it.

I realized it was actually mentioned on the release ticket. If anyone else is looking, here is the ticket #120 .

Looking forward to it!

from nest.

cojack avatar cojack commented on April 24, 2024

@kamilmysliwiec how does v4 influence on this issue?

from nest.

kamilmysliwiec avatar kamilmysliwiec commented on April 24, 2024

Hi @cojack,
The @nestjs/swagger package is in alpha version, I need to publish it as a separated repo 🙂

from nest.

cojack avatar cojack commented on April 24, 2024

@kamilmysliwiec waiting so much 👍

from nest.

zackarychapple avatar zackarychapple commented on April 24, 2024

@valorkin this is what Georgii needed for our swagger docs. :)

from nest.

valorkin avatar valorkin commented on April 24, 2024

As far as I know, swagger was renamed to Open API

from nest.

VinceOPS avatar VinceOPS commented on April 24, 2024

@kamilmysliwiec
Yup, would like to help too. Nestjs is a very good project. Slowly starting to enjoy writing Express API's with it :D. Thanks for your work, Kamil.

from nest.

MaheshCasiraghi avatar MaheshCasiraghi commented on April 24, 2024

@kamilmysliwiec any chance you can share the work in progress of the tutorial?

from nest.

MaheshCasiraghi avatar MaheshCasiraghi commented on April 24, 2024

Hello @darioxtx: 2 questions related to your answer (sorry for noobying, I am kind of new to nest :-)):

  1. how do you have access to (i.e., inject) the 'app' object within the swagger controller?
  2. what is the RequestException object?

Thank you!

from nest.

darioxtx avatar darioxtx commented on April 24, 2024

My bad, you should use SwaggerModule in app bootstrap function.
I updated example.

from nest.

qinyang1980 avatar qinyang1980 commented on April 24, 2024

@kamilmysliwiec, amazing work. This is just what I want.
You must have been a Java Spring Boot developer.

from nest.

LuukMoret avatar LuukMoret commented on April 24, 2024

@kamilmysliwiec Yes, very nice indeed! Any ETA on the GraphQL recipe? Really curious about that one as well

from nest.

arielweinberger avatar arielweinberger commented on April 24, 2024

@marcelfalliere
SwaggerModule.createDocument(), take a look at the example above posted by @darioxtx .

For example:

  const document = SwaggerModule.createDocument(app, options);
  writeFile('swagger/my-service.json', JSON.stringify(document), 'utf8');

You can then serve this static file from any web server you'd like.
For instance, you could create a lightweight http-server instance that you run by npm run swagger.

You don't have to use app.listen(). You could use Swagger UI to present your output .json file.

from nest.

lock avatar lock commented on April 24, 2024

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.

from nest.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.