Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
swagger-jsdoc
Advanced tools
swagger-jsdoc is a Node.js library that allows you to integrate Swagger/OpenAPI documentation into your Express.js or other Node.js applications. It generates the Swagger specification based on JSDoc comments in your code, making it easier to maintain and update API documentation.
Generate Swagger Documentation
This feature allows you to generate Swagger documentation from JSDoc comments in your code. The `options` object specifies the OpenAPI version, API info, and the files containing the JSDoc comments.
const swaggerJsdoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Express API with Swagger',
version: '1.0.0',
},
},
apis: ['./routes/*.js'], // files containing annotations as above
};
const swaggerSpec = swaggerJsdoc(options);
Integrate with Express
This feature demonstrates how to integrate Swagger UI with an Express application. The Swagger documentation is served at the `/api-docs` endpoint.
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');
const app = express();
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Express API with Swagger',
version: '1.0.0',
},
},
apis: ['./routes/*.js'],
};
const swaggerSpec = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
JSDoc Annotations
This feature shows how to use JSDoc annotations to document an API endpoint. The annotations provide metadata about the endpoint, such as the HTTP method, summary, and response schema.
/**
* @swagger
* /users:
* get:
* summary: Retrieve a list of users
* responses:
* 200:
* description: A list of users
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* id:
* type: integer
* name:
* type: string
*/
app.get('/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
swagger-ui-express is a middleware for Express.js that serves auto-generated Swagger UI. It is often used in conjunction with swagger-jsdoc to serve the generated Swagger documentation. While swagger-jsdoc focuses on generating the Swagger specification, swagger-ui-express focuses on serving it in a user-friendly interface.
openapi-generator is a tool that can generate client libraries, server stubs, API documentation, and configuration from an OpenAPI Specification. Unlike swagger-jsdoc, which generates the OpenAPI spec from JSDoc comments, openapi-generator takes an existing OpenAPI spec and generates code and documentation from it.
redoc is a tool for generating API documentation from OpenAPI specifications. It provides a customizable and responsive HTML documentation. Unlike swagger-jsdoc, which generates the OpenAPI spec, redoc focuses on rendering the documentation from an existing spec.
swagger-jsdoc enables to integrate Swagger using JSDoc.
$ npm install swagger-jsdoc --save
swagger-jsdoc returns the validated swagger specification as JSON.
var swaggerJSDoc = require('swagger-jsdoc');
var options = {
swaggerDefinition: {
info: {
title: 'Hello World', // Title (required)
version: '1.0.0', // Version (required)
},
},
apis: ['./routes.js'], // Path to the API docs
};
// Initialize swagger-jsdoc -> returns validated swagger spec in json format
var swaggerSpec = swaggerJSDoc(options);
At this time you can do with the swaggerSpec whatever you want. The simplest way would be serving it straight to the outside world:
app.get('/api-docs.json', function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
You could also use a framework like swagger-tools to serve the spec and a swagger-ui.
The API can now be documented in JSDoc-style with swagger spec in YAML.
/**
* @swagger
* /login:
* post:
* description: Login to the application
* produces:
* - application/json
* parameters:
* - name: username
* description: Username to use for login.
* in: formData
* required: true
* type: string
* - name: password
* description: User's password.
* in: formData
* required: true
* type: string
* responses:
* 200:
* description: login
*/
app.post('/login', function(req, res) {
res.json(req.body);
});
A model may be the same for multiple endpoints (Ex. User POST,PUT responses). In place of writing (or copy and pasting) the same code into multiple locations, which can be error prone when adding a new field to the schema. You can define a model and re-use it across multiple endpoints. You can also reference another model and add fields.
/**
* @swagger
* definitions:
* NewUser:
* type: object
* required:
* - username
* - password
* properties:
* username:
* type: string
* password:
* type: string
* format: password
* User:
* allOf:
* - $ref: '#/definitions/NewUser'
* - required:
* - id
* - properties:
* id:
* type: integer
* format: int64
*/
/**
* @swagger
* /users:
* get:
* description: Returns users
* produces:
* - application/json
* responses:
* 200:
* description: users
* schema:
* type: array
* items:
* $ref: '#/definitions/User'
*/
app.get('/users', function(req, res) {
res.json([ {
id: 1,
username: 'jsmith',
}, {1
id: 2,
username: 'jdoe',
} ]);
});
/**
* @swagger
* /users:
* post:
* description: Returns users
* produces:
* - application/json
* parameters:
* - name: user
* description: User object
* in: body
* required: true
* type: string
* schema:
* $ref: '#/definitions/NewUser'
* responses:
* 200:
* description: users
* schema:
* $ref: '#/definitions/User'
*/
app.post('/users', function(req, res) {
// Generate ID
req.body.id = Math.floor(Math.random() * 100) * 1
res.json(req.body);
});
You can load external definitions or paths after swaggerJSDoc()
function.
// Initialize swagger-jsdoc -> returns validated swagger spec in json format
var swaggerSpec = swaggerJSDoc(options);
// load external schema json
swaggerSpec.definitions.in_login = require("config/schemajson/in.login.schema.json");
swaggerSpec.definitions.out_login = require("config/schemajson/out.login.schema.json");
// or set manual paths
swaggerSpec.paths["api/v1/cool"] = {"get" : { ... } }
};
There is an example app in the example subdirectory. To use it you can use the following commands:
$ git clone https://github.com/Surnet/swagger-jsdoc.git
$ cd swagger-jsdoc
$ npm install
$ npm start
The swagger spec will be served at http://localhost:3000/api-docs.json
If the module is installed globally, a command line helper $ swagger-jsdoc
will be available.
Otherwise ./bin/swagger-jsdoc
accesses to the same interface.
Common usage:
./bin/swagger-jsdoc -h
./bin/swagger-jsdoc -d example/swaggerDef.js
- could be any .js or .json file which will be require()
-ed and parsed/validated as JSON../bin/swagger-jsdoc example/routes.js example/routes2.js
- free form input, can be before or after definition./bin/swagger-jsdoc -o output.json
- swagger.json will be created if this is not set.
If specifying an output file with a .yaml
or .yml
extension, the swagger spec will automatically be saved in YAML format instead of JSON../bin/swagger-jsdoc -d example/swaggerDef.js example/routes.js example/routes2.js -w
- start a watch task for input files with API documentation.
This may be particularly useful when the output specification file is integrated with Browsersync
and Swagger UI. Thus, the developer updates documentation in code with fast feedback in an
interface showing an example of live documentation based on the swagger specification.FAQs
Generates swagger doc based on JSDoc
The npm package swagger-jsdoc receives a total of 688,205 weekly downloads. As such, swagger-jsdoc popularity was classified as popular.
We found that swagger-jsdoc demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.