Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@smartrecruiters/openapi-first

smartrecruiters70MIT1.2.0

Start your node REST app with designing API first!

readme

@smartrecruiters/openapi-first

NPM Version NPM Downloads Node.js Version Licence Build

Start your node REST app with designing API first!

Is it for you?

If you:

  • use OpenAPI Specification 3.0 to document your REST APIs written in node.js,
  • like design first approach regarding REST APIs
  • want your specification to be single source of truth of your API,
  • want to handle validation and parsing of requests query, path, body, content-type in a unified manner for all API endpoints,

then @smartrecruiters/openapi-first is what you are looking for!

This module initializes your API connect-style application with specification in OpenAPI Specification 3.0 format.

How to start

Let's say you have specification in OpenAPI Specification 3.0 in spec.json:

{
    "openapi": "3.0.0",
    "info": {
        "version": "1.0.0",
        "title": "Hello World API"
    },
    "paths": {
        "/hello": {
            "get": {
                "responses": {
                    "200": {
                        "description": "Success",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/Greeting"
                                }
                            }
                        }
                    }
                },
                "x-swagger-router-controller": "greeting/hello",
                "parameters": [
                    {
                        "in": "query",
                        "name": "name",
                        "schema": {
                            "type": "string",
                            "default": "world"
                        }
                    }
                ]
            }
        }
    },
    "components": {
        "schemas": {
            "Greeting": {
                "type": "object",
                "properties": {
                    "greeting": {
                        "type": "string"
                    }
                }
            }
        }
    }
}

Now you can implement connect-style middleware with "business logic" in greeting/hello.js:

module.exports = function(req, res) {
    res.status(200).json({greeting: `Hello, ${req.query.name}!`})
}

Now, let's make an app.js file:

const openApiFirst = require('@smartrecruiters/openapi-first')
const express = require('express')

// create express app
const app = express()

const spec = require('./spec.json')

// create open api specification initializer
const api = openApiFirst(app, spec)

// to enable setting default values on empty query params
api.use(require('@smartrecruiters/openapi-first/middlewares/query/defaults')())

// to link the specification with code in 'api' directory
api.use(require('@smartrecruiters/openapi-first/middlewares/controllers/by-property')({dir: __dirname}))

app.listen(8080)

We can now run the application:

node app

To verify it's working, let's hit the endpoint:

curl localhost:8080/hello?who=world

The response should be 200 with body:

{"greeting":"Hello, world!"}

openapi middlewares

You can use one of the middlewares under @smartrecruiters/middlewares/* or create your own. Such middlewares will be applied to connect-style app for each operation as they are specification and operation aware. For instance, @smartrecruiters/middlewares/query/validate middleware will be applied to any and only operation which has query parameters defined, passing an Error to next callback when req.query is invalid.

Currently following middlewares are available:

  • request body validation,
  • request body parsing (e.g. form string parameters to types specified in API documentation)
  • setting default values on request body,
  • query parameters validation,
  • setting default query parameters values
  • removing unspecified query parameters,
  • path parameters validation,
  • content type validation,
  • routing to appropriate controller,
  • oauth scopes authorization,
  • error handlers (MissingRequiredScopes).

Validation middlewares

Middlewares for request body, query and path validation expects schema validators in order to be created. The recommended schema validator is @smartrecruiters/openapi-schema-validator

Create your own openapi middleware

Adding your own openapi is very simple. Let's say your operation has extension OpenAPI Specification 3.0 Specification Extension 'x-only-admin'. If it is set on, this will mean that only users with admin can use this method. Assuming some preceding middleware is setting req.user.role, you can write a simple openapi middleware that will gather information from operation object and act accordingly:

const onlyAdminMiddleware = operation =>
    (req, res, next) => {
        if(operation['x-only-admin'] && req.user.role !== "admin") {
            res.status(403).json("Access forbidden. For this operation, you need to have admin role")
        }
        return next()
    }

Contributing

Please see our Code of conduct and Contributing guidelines

License

MIT

changelog

1.2.0 (2024-07-08)

  • Creates middleware for path parameters validation

1.1.0 (2021-07-08)

  • feat: resolve refs nested under .schema property (#31) (497aa74), closes #31

1.0.1 (2021-07-08)

  • BREAKING CHANGE: drop support for Node < 10 (#33) (65c67f3), closes #27 #33
  • feat: update dependencies (#33) (65c67f3), closes #30

0.4.2 (2019-07-22)

  • Remove uuid dependency & update dependencies (#29) (a710252), closes #29

0.4.1 (2019-07-18)

  • ISSUE-7 - fix middleware for inclusive paths (#28) (ca5269c), closes #28

0.4.0 (2019-05-30)

  • OAuth scopes error handler with WWW-Authenticate header (#25) (1162064), closes #25
  • Update dependencies (#26) (7f47f6d), closes #26

0.3.2 (2019-04-26)

0.3.1 (2019-03-29)

  • by-property controller middleware handles rejected promises (#19) (82b9d9a), closes #19

0.3.0 (2019-03-06)

  • Missing scopes error handler (#17) (2aae9c0), closes #17

0.2.0 (2019-02-28)

  • Introduce new middleware for oauth scopes verification (#15) (34f1984), closes #15

0.1.3 (2018-12-21)

  • Empty query param case handled for query params of type (#14) (d25f556), closes #14
  • Update dependencies (#11) (13864ea), closes #11

0.1.2 (2018-05-22)

  • Using defaultsDeep causes that values for array type of parameters are merged with default value (f24cee1), closes #6

0.1.1 (2018-05-10)

  • node.js version in package.json (c4b14f8)
  • README typo fix (#2) (feca553), closes #2
  • Update dependencies (#4) (0ff2c40), closes #4

0.1.0 (2018-03-12)

  • Init @smartrecruiters/openapi-first (49090fc)