I'm using Node.js and Swagger to build a restful API. The Swagger UI (demo link here http://petstore.swagger.io/) requires a JSON feed.
How would you generate this feed based on the Swagger spec yaml file? Is there not a npm module that can iterate over the yaml file and generate the JSON feed? I'm new to Swagger so I might have overlooked something.
Swagger UI should support YAML by now. You can convert YAML to JSON using JSYAML library.
You can also use the Swagger Editor:
http://editor.swagger.io/#/
I can't say I have tried it before, but you can upload YAML and export as YAML or JSON.
I have used the editor before and do really like it.
EDIT:
So to setup the swagger ui I did the following:
var swaggerUi = new SwaggerUi({
url:"http://petstore.swagger.io/v2/swagger.json",
dom_id:"swagger-ui-container"
});
swaggerUi.load();
That comes from here:
https://github.com/swagger-api/swagger-ui
I think you got that part.
As for the doc (YAML or JSON) just serve it out from your site. If you are using express with your nodejs server just serve out the file statically:
http://expressjs.com/starter/static-files.html
app.use('/static', express.static('public'));
So in this case if you put the swagger.json file right under your public dir you can access it with:
http://<yoursite>/swagger.json
Just test that you can actually get to your swagger docs from that url in the browser. Put that URL into the 'url' parameter above when you setup swagger-ui and you should be go to go. Swagger-ui will do the rest for you, it will pull the json or yaml definition from your site and generate the interactive docs site.
Related
We have many APIs written in nodejs, using nestjs framework.
We can generate openapi.yaml using SwaggerModule from nestjs. that works perfectly. But the problem is that it needs the API to be up, and therefore that the database is up and running. That's a problem for us in our CI/CD, because we need to generate openapi specification before running the API.
Is it possible to generate openapi specification from our code, without needing to run the application?
Or maybe is there a simple way to mock our database?
Thanks for your help
The short answer is no, there isn't a way to generate the docs without running the NestJS application. However, you can generate a JSON file representing the OpenAPI documentation and then generate a static website from there. This issue gets you half-way there:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const options = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, options);
const outputPath = path.resolve(process.cwd(), 'swagger.json');
writeFileSync(outputPath, JSON.stringify(document), { encoding: 'utf8'});
await app.close();
}
bootstrap();
This will generate a file swagger.json containing the OpenAPI specification. From there, you can use a tool like Spectacle to generate the actual HTML:
npx spectacle-docs -t public/docs swagger.json
An even less documented feature is the ability to retrieve a JSON representation of the OpenAPI specification from the regular endpoint using only curl.
Let's say you have a standard #nestjs/swagger integration that publishes the OpenAPI docs to /docs/:
const options = new DocumentBuilder()
.setTitle('core-api')
.setDescription('The core API description')
.setVersion('3.0')
.addTag('core-api')
.setBasePath(version)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('docs', app, document);
If you browser to http:/localhost:3000/docs/, you can access the HTML version of the docs. However, if you browser to http://localhost:3000/docs-json you will receive a JSON representation. Simply append -json to whatever you spec path is.
Tying this all together, you can integrate this into a CI pipeline with a little hackery. I have integrated this into a Gitlab CI pipeline like so:
script:
- until nc -vz $API_IP 3000; do sleep 1; done
- curl http://$API_IP:3000/docs-json -o swagger.json
- npx spectacle-docs -t public/docs swagger.json
In your CI pipeline, you'll still have to run your NestJS application and as well as Mongo and any other dependant services required for it to start, but once you generate the JSON you can stop your application, build the static HTML site and publish it elsewhere.
I managed to generate the swagger spec from my e2e tests without starting the server
generating swagger json file without running nest js server
I am able to configure swagger url using the Express API with autogenerated OpenAPI doc through Swagger article.
I am using TypeScript and it generates .js files under dist which does not have any API doc comments added. Pointing apis: ['../dist/*.js'] nor to Route.ts generates the API details. I am not using any rest decorator.
/**
* #swagger
* /:
* get:
* description: This should return ok
*/
this.router.get("/", (req: Request, res: Response) => this.api.process(req, res));
The Routes.ts API doc looks like the above. How to generate swagger doc from this?
I would recommend that you use a library that handles everything for you such as tsoa which can easily generate Swagger/OpenAPI documents from your TypeScript types. It also does the runtime validation for you so that you know the request actually is the type that TypeScript says it should be. 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 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 am currently working on an application with the current tech stack:
Backend:
Mongoose
Express
Apollo
GraphQL
Frontend:
Vuejs
Apollo
GraphQL
I have succeeded in uploading files to the server using GraphQL, what I am stuck with is how to implement the 'download' feature. With a normal RESTApi endpoint I can use res.download(filePath) and it works. How do I do this with GraphQL since I don't want to use REST.
Or is there any other standard to go by in this scenario?
Thanks!
GraphQL uses JSON format, which represents as text format, not as binary.
If you don't want download files with REST, then you should:
Encode your file content into base64 string in the back end. Related question
Send this string as part of query response.
Save encoded base64 string as a file in the front end. Related question
But right architecture design is add a file link in the GraphQL response and use browser for downloading/rendering the file.
It's better to send a hashed & temporary link to download it
Save the file and hash the name on your static server (to limit access to other users)
The file should be temporary and should expire in a short time
Send the link of the file in response to API
I have Swagger 2.0 documentation, and I would like to create a Node.JS server stub from the existing Swagger spec.
When I use the Swagger Editor, it has the option to generate Node.js server stubs, but the generated file uses the connect NPM libraries.
I would prefer to use Express, and have the application folder structure of a general Express application. Is there a way to modify the generation of the Node.JS server stub to be compatible with Express?
The easy answer is to change var app = require('connect')(); to var app = require('express')(); in nodejs-server-server/index.js. But it's not optimal since the generated code does not take use of the functionality of Express.
It seems like there will be a express code generator in the next version of swagger-codegen.
You could also use swaggerize-express to do the server stub generation.
According to Swagger website, there are two approaches: Bottom-up and Top-down.
I have an existing NodeJS server that I'd like to deploy in the Azure enviroment, that require a swagger document (API APP).
Does anyone know a tool for generating the swagger using the code? Even better if you could point a tutorial. I couldn't find it.
Question is a bit old but still. It is possible to generate completely automatically Swagger (OpenAPI) specification just by embedding analysis middleware like this: https://github.com/mpashkovskiy/express-oas-generator
const express = require('express');
const expressOasGenerator = require('express-oas-generator');
let app = express();
expressOasGenerator.init(app, {});
run some client or REST API tests agains your service and open http://host:port/api-docs
It’s not difficult to integrate Swagger in exist express applications following this tutorial.
Generally, we can follow these steps:
Add the dependencies in our package.json, and run npm install to install them. The dependencies should be:
"dependencies": {
"swagger-node-express": "~2.0",
"minimist": "*",
"body-parser": "1.9.x",
...
}
Download the zip project of Swagger-UI, copy the dist folder into the root directory of our project, the directory should almost like:
Introduce the dependencies at the beginnng of app.js:
var argv = require('minimist')(process.argv.slice(2));
var swagger = require("swagger-node-express");
var bodyParser = require( 'body-parser' );
Set up a subpath for swagger doc:
var subpath = express();
app.use(bodyParser());
app.use("/v1", subpath);
swagger.setAppHandler(subpath);
Make sure that /dist is able to serve static files in express:
app.use(express.static('dist'));
Set the info for API:
swagger.setApiInfo({
title: "example API",
description: "API to do something, manage something...",
termsOfServiceUrl: "",
contact: "yourname#something.com",
license: "",
licenseUrl: ""
});
Introduce /dist/index.html for swagger UI:
subpath.get('/', function (req, res) {
res.sendfile(__dirname + '/dist/index.html');
});
Complete the swagger configurations:
swagger.configureSwaggerPaths('', 'api-docs', '');
var domain = 'localhost';
if(argv.domain !== undefined)
domain = argv.domain;
else
console.log('No --domain=xxx specified, taking default hostname "localhost".');
var applicationUrl = 'http://' + domain;
swagger.configure(applicationUrl, '1.0.0');
Configure doc file dependence in /dist/index.html:
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
<del>url = "http://petstore.swagger.io/v2/swagger.json";</del>
url = "/api-docs.json";
}
Create api-docs.json file with the info of your APIs, put it in the dist folder.
Run the Express app on local, visit http://localhost:3000/v1, we can check the swagger doc.
Here is my test sample repo for your reference.
To my knowledge, your options are:
Using swagger-node-express which is very cumbersome in my opinion.
Writing up the swagger document manually yourself with the help of swagger editor as suggested in this SO Answer
If you go for option 2, you could use swagger-ui-express to generate the swagger-ui
A lot of developers are still having this problem so I built an open-source tool to help -- the tool is kind of like Git for APIs. It works by running a proxy while you're developing the API, analyzing the traffic, and updating the spec for you as the API's behavior changes. Hopefully, the workflow saves you a lot of time: https://github.com/opticdev/optic
Most alternatives require some sort of API specification through Json, Yaml or even embedded in JSdocs. On the other hand there are some runtime analyzers intercepting HTTP requests and building that specification on-demand.
express-sitemap-html follows a different approach inspecting the express object and its routes at setup time. Thus it always provides an up-to-date swagger UI for installed routes on existing express instance.
const sitemap = require('express-sitemap-html')
...
sitemap.swagger('Title', app) // app is an express instance
Then get swagger UI from your domain /api-docs.