Skip to content

Instantly share code, notes, and snippets.

@AD0791
Last active August 17, 2021 20:09
Show Gist options
  • Save AD0791/25a33914830a1ccd949f56f3f981e2eb to your computer and use it in GitHub Desktop.
Save AD0791/25a33914830a1ccd949f56f3f981e2eb to your computer and use it in GitHub Desktop.
simple swagger usage with express
const express = require("express");
const app = express();
const swaggerJsDoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const port = process.env.PORT || 5000;
// Extended: https://swagger.io/specification/#infoObject
const swaggerOptions = {
swaggerDefinition: {
info: {
version: "1.0.0",
title: "Customer API",
description: "Customer API Information",
contact: {
name: "Amazing Developer"
},
servers: ["http://localhost:5000"]
}
},
// ['./routes/*.js']
apis: ["app.js"]
};
app.use(express.urlencoded({ extended: true }))
app.use(express.json());
app.use(morgan('tiny'));
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs));
// Routes
/**
* @swagger
* /customers:
* get:
* description: Use to request all customers
* tags: [customers]
* responses:
* '200':
* description: A successful response
*/
app.get("/customers", (req, res) => {
res.status(200).send("Customer results");
});
/**
* @swagger
* /customers:
* put:
* description: Use to return all customers
* tags: [customers]
* parameters:
* - name: customer
* in: query
* description: Name of our customer
* required: false
* schema:
* type: string
* format: string
* responses:
* '201':
* description: Successfully created user
*/
app.put("/customer", (req, res) => {
res.status(200).send("Successfully updated customer");
});
/**
* @swagger
* components:
* schemas:
* register:
* type: object
* required:
* - worker_id
* - worker_first_name
* - worker_last_name
* - name
* - description
* - quantity
* - item_classification
* properties:
* worker_id:
* type: integer
* worker_first_name:
* type: string
* worker_last_name:
* type: string
* name:
* type: string
* description:
* type: string
* quantity:
* type: integer
* item_classification:
* type: string
*/
/**
* @swagger
* tags:
* name: post register
* description: A worker will post a register
*/
/**
* @swagger
* /register:
* post:
* description: post and create a register
* tags: [post register]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/register'
* responses:
* '201':
* description: Successfully created register
*/
app.post("/register", (req, res) => {
debug(req.body)
res.status(201).json(req.body);
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment