Giter Site home page Giter Site logo

openapi-first's Introduction

@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 regardign REST APIs
  • want your specification to be single source of truth of your API,
  • want to handle validation and parsing of requests query, 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 instace, @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,
  • content type validation,
  • routing to appropriate controller,
  • oauth scopes authorization,
  • error handlers (MissingRequiredScopes).

Validation middlewares

Middlewares for request body and query 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

openapi-first's People

Contributors

abdulrahman-khankan avatar annalesniak avatar dependabot[bot] avatar kasinskim avatar kiebzak avatar rafalsiwiec 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

Watchers

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

openapi-first's Issues

Query params parsing behaves unpredictably

Given a parameter definition:

arrayInQuery:
  in: query
  name: arr
  required: true
  schema:
    type: array
    items:
      type: string

and using @smartrecruiters/openapi-first/middlewares/query/parse middleware within express results in setting the value of arr parameter to empty string.
When combined with @smartrecruiters/openapi-first/middlewares/query/validate - request is rejected because of type of value stored in parameter is not an array.

Use of operationId for route matching

The router seems to use x-swagger-router-controller to match a route to a controller action. It would be better to use the operationId for this purpose so that the OAS spec remains unchanged when using this package and is easily portable anywhere else.
It is possible to allow for dotted operationId such as greeting.hello and translate each segment to a folder in a hierarchical form so that controllers/handlers can be modularized into folders. It's possible to use _ instead of . or any other separator.

[How-To] controller by operation name

Trying to use a controller that has 1+ operations, need help/suggestion on how to configure. The by-property controller only considers x-swagger-router-controller and don't know how to make use of operationid.

OAuth scopes error handler

missing-scopes error handler seems not to be fully compatible with The OAuth 2.0 standard.

The information about insufficient scope should be passed in WWW-Authenticate response header with auth-scheme name followed by scope, error and error_description properties (as stated here: https://tools.ietf.org/html/rfc6750#section-3 and the following sections of the standard).

Added label enhancement as it should lead to removal of the message from the response body and as a result breaking change.

Handle rejected promises in by-property controller-middleware

Currently, when using @smartrecruiters/openapi-first/middlewares/controllers/by-property together with async&await controllers you have to try&catch the whole logic to ensure that thrown error is propagated to next.
Mentioned above middleware could handle this situation.

oauth example

Can you please provide an example that includes the use of oauth in the spec (and in the code).

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.