Giter Site home page Giter Site logo

bee-travels / openapi-comment-parser Goto Github PK

View Code? Open in Web Editor NEW
254.0 12.0 29.0 2.43 MB

⚓️ JSDoc Comments for the OpenAPI Specification

License: Apache License 2.0

JavaScript 38.44% TypeScript 22.20% HTML 0.57% CSS 38.78%
swagger express openapi jsdoc

openapi-comment-parser's Introduction

OpenAPI Comment Parser
npm Version travis npm Downloads

A clean and simple way to document your code for generating OpenAPI (Swagger) specs.

Goal

goal

Installation

$ npm install openapi-comment-parser --save

or

$ yarn add openapi-comment-parser

Usage

Create a yaml file with a base OpenAPI definition:

openapi: 3.0.0
info: 
  title: Title of your service
  version: 1.0.0

Add the following to your code:

const openapi = require('openapi-comment-parser');

const spec = openapi();

Swagger UI Express example

Swagger UI Express is a popular module that allows you to serve OpenAPI docs from express. The result is living documentation for your API hosted from your API server via a route.

const openapi = require('openapi-comment-parser');
const swaggerUi = require('swagger-ui-express');

const spec = openapi();

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(spec));

Configuration options

There are several configuration options for parsing. For example, including and excluding certain files and paths:

const spec = openapi({
  exclude: ['**/some/path/**']
});

Options

Option name Default
cwd The directory where commentParser was called
extension ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.yaml', '.yml']
include ['**']
exclude A large list that covers tests, coverage, and various development configs
excludeNodeModules true
verbose true
throwLevel off

CLI

npm install -g openapi-comment-parser

(optional) generate a .openapirc.js config file:

openapi-comment-parser --init

Generate an openapi.json file:

openapi-comment-parser . openapi.json

Eslint plugin

To enable linting of the OpenAPI jsdoc comments, install the eslint plugin:

$ npm install eslint-plugin-openapi --save-dev

or with yarn:

$ yarn add -D eslint-plugin-openapi

Then create an .eslintrc.json:

{
  "extends": ["plugin:openapi/recommended"]
}

Basic structure

You can write OpenAPI definitions in JSDoc comments or YAML files. In this guide, we use only JSDoc comments examples. However, YAML files work equally as well.

Each comment defines individual endpoints (paths) in your API, and the HTTP methods (operations) supported by these endpoints. For example, GET /users can be described as:

/**
 * GET /users
 * @summary Returns a list of users.
 * @description Optional extended description in CommonMark or HTML.
 * @response 200 - A JSON array of user names
 * @responseContent {string[]} 200.application/json
 */

Parameters

Operations can have parameters passed via URL path (/users/{userId}), query string (/users?role=admin), headers (X-CustomHeader: Value) or cookies (Cookie: debug=0). You can define the parameter data types, format, whether they are required or optional, and other details:

/**
 * GET /users/{userId}
 * @summary Returns a user by ID.
 * @pathParam {int64} userId - Parameter description in CommonMark or HTML.
 * @response 200 - OK
 */

For more information, see Describing Parameters.

Request body

If an operation sends a request body, use the bodyContent keyword to describe the body content and media type. Use bodyRequired to indicate that a request body is required.

/**
 * POST /users
 * @summary Creates a user.
 * @bodyContent {User} application/json
 * @bodyRequired
 * @response 201 - Created
 */

For more information, see Describing Request Body.

Responses

For each operation, you can define possible status codes, such as 200 OK or 404 Not Found, and the response body content. You can also provide example responses for different content types:

/**
 * GET /users/{userId}
 * @summary Returns a user by ID.
 * @pathParam {int64} userId - The ID of the user to return.
 * @response 200 - A user object.
 * @responseContent {User} 200.application/json
 * @response 400 - The specified user ID is invalid (not a number).
 * @response 404 - A user with the specified ID was not found.
 * @response default - Unexpected error
 */

For more information, see Describing Responses.

Input and output models

You can create global components/schemas section lets you define common data structures used in your API. They can be referenced by name whenever a schema is required – in parameters, request bodies, and response bodies. For example, this JSON object:

{
  "id": 4,
  "name": "Arthur Dent"
}

can be represented as:

components:
  schemas:
    User:
      properties:
        id:
          type: integer
        name:
          type: string
      # Both properties are required
      required:  
        - id
        - name

and then referenced in the request body schema and response body schema as follows:

/**
 * GET /users/{userId}
 * @summary Returns a user by ID.
 * @pathParam {integer} userId
 * @response 200 - OK
 * @responseContent {User} 200.application/json
 */

/**
 * POST /users
 * @summary Creates a new user.
 * @bodyContent {User} application/json
 * @bodyRequired
 * @response 201 - Created
 */

Authentication

The securitySchemes and security keywords are used to describe the authentication methods used in your API.

components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic
/**
 * GET /users
 * @security BasicAuth
 */

Supported authentication methods are:

  • HTTP authentication: Basic, Bearer, and so on.
  • API key as a header or query parameter or in cookies
  • OAuth 2
  • OpenID Connect Discovery

For more information, see Authentication.

openapi-comment-parser's People

Contributors

bourdakos1 avatar maxshapiro32 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openapi-comment-parser's Issues

Request body tables aren't as good as they could be

right now we just list the root json and the schema it relies on for example:

Request Body
{ friends: Person[] }
Person
{ name: string }

we should do something like this maybe?

Request Body
friends Person[]
A list of friends
Person
name string — REQUIRED
The name of the person

Or maybe nested tables?

Request Body
friends Person[]
A list of friends
name string — REQUIRED
The name of the person
firstname string — REQUIRED
Your firstname
middle string
Your middle initial
lastname string — REQUIRED
Your firstname

check that schemas have been defined

example:

/**
 * GET /pets/{id}
 * @pathParam {strng} id - The id of the pet.
 * @response 200 - OK
 */

The schema strng hasn't been defined and is not a primitive, they probably meant string so it would be nice to have an eslint error

we can't just check the primitive list because they could have strng defined as a schema component

Usage with NextJS

I'm trying to use this with NextJS, but I'm not sure how. Running the CLI produces an empty-ish json file (shown below)

{"openapi":"3.0.0","info":{"title":"Title of your service","version":"1.0.0"},"paths":{},"components":{}}

param examples have no effect on UI

If a param has an example, the UI should use the example as the placeholder for the text input and render an example in the params table.

Example:

components:
  schemas:
    CurrencyCode:
      type: string
      example: USD
/**
 * GET /currency/{code}
 * @pathParam {CurrencyCode} code - A three letter currency code.
 * @response 200 - OK
 */

should render:

Path Params
code string[] - REQUIRED
A three letter currency code.
Example: USD

with a try it out example:
code

USD

Generate md/swagger.yaml from comments?

What am I trying to accomplish

We have various github repos and I would like to generate the docs in an md file that can then be used to refer to the API. Currently I have these comments and from them I can generate the swagger.yml file. Is it possible to do something similar with this package?

Would it be possible to generate a swagger file from the spec instead of exposing the endpoint.

How to use with import

Hey 👋

Node 12+ has import support, as soon as I change require to import openapi starts to generate nothing. Tested on repo example.

Is there a way to use this great package with imports?

Integrating with input validation

I know this is out of the scope of this library, but I am asking here to see if someone have already given a thought about this and solved it somehow within the openapi ecosystem.

A lot of boilerplate in any api service has to do with validating user's input. There are all kind of json schema validators and if you're using Typescript, you can use something like class-validator to decorate your classes and validate the user's input according to the requirements.

Ideally, we should write the openapi definitions one time in our code base with openapi-comment-parser syntax and then somehow use it to validate the requests according to the spec. I guess this will require "compiling" the comments into a openapi spec file and then using one of the validators to verify the user's input.

Has anyone tried anything like this before and can suggest an approach that worked for them ?

Thank you for this library

response examples aren't displayed

Show a response table just above the status codes (maybe below...?)

it's possible to have many examples and many content types, we might simplify to only using one

need to implement authentication

A user should be able to click an authenticate button to log in and generate the proper credentials to send with each request according to their OpenAPI spec

Dynamic spec definitions

Hi, I have a use case where i would like to set title and/or version of spec definition dynamically, based on current environment or api version. Currently, it seems that this is not so straightforward with yaml.

const definition = {
  openapi: '',
  info: {
    title: '',
    version: '', // < -- these should be set dynamically, not parsed from static yaml file, if possible
  },
};

Would love the option to pass spec definitions to the parser, either as a part of the ParserOptions in openapi(options: ParserOptions) or as a second argument.
Or, maybe there is already solution for this and i'm missing something :/ .

If not, i'm also open to creating PR for this feature.

Btw, big fan of this project, thanks for creating it 👍 .

How can I show an array of objects?

Hi Guys,

Love this!! Really makes building OpenAPI documentation.

However I am struggling to find the right code to put my example response inside an Array.

I have a single result working e.g GET /User

{ id: 1 name: "Andy" }

However I would like GET /Users to show

[{ id: 1 name: "Andy" }]

I cannot for the life of me get the object inside an [ ] elements.

Thanks.

Codegen colors

Some of the codegen colors aren't dynamic yet so they look bad in light mode

File Type Support

Not really an issue but more of a request. Are ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.yaml', '.yml'] the only file types supported? This is a really useful tool for my process. I would love support for '.java' files? CLI usage only obviously.

Cheers!

Handle streams?

Maybe we should add support for video streams and maybe some sort of socket support?

Request samples

Hi There,

Is there a way to include an example Request sample?

I am including example response but would be great to show an example request, so rather than:

{
"id": 0,
"status": "string",
"currency": "string",
"date_modified": { },
"discount_total": 0,
"shipping_total": 0,
"total_tax": 0,
"total": 0,
"billing": { },
"shipping": { },
"payment_method": "string",
"transaction_id": "string",
"customer_note": "string",
"meta_data": { },
"line_items": [ ],
"coupons": [ ],
"shipping_method": "string"
}

It could be something like:

{
"id": "AS0001",
"status": "processing",
"currency": "USD",
"date_modified": {
"date": "2021-03-19 12:32:55",
"timezone_type": 1,
"timezone": "+00:00"
},
"discount_total": 0,
"discount_tax": 0,
"shipping_total": 0,
"shipping_tax": 0,
"cart_tax": 0,
"total": 0.99,
"total_tax": 0,
"billing": {
"company": "Shoreline Lake American Bistro",
"first_name": "Andrew",
"last_name": "Slack",
"address_1": "3160 N Shoreline Blvd",
"address_2": "",
"city": "Mountain View",
"postcode": "94043",
"state_name": "CA",
"country": "US",
"email": "[email protected]"
},
"shipping": {
"company": "Shoreline Lake American Bistro",
"first_name": "Andrew",
"last_name": "Slack",
"address_1": "3160 N Shoreline Blvd",
"address_2": "",
"city": "Mountain View",
"postcode": "94043",
"state_name": "CA",
"country": "US",
"email": "[email protected]"
},
"payment_method": "",
"transaction_id": 0,
"customer_note": "",
"meta_data": { },
"line_items": [
{}
],
"coupons": [ ],
"shipping_method": "Standard Shipping"
}

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.