LoginSignup
5
1

More than 3 years have passed since last update.

expressでOpenAPI仕様のAPIを実装するときのTips

Posted at

要点

  1. express-openapiを使おう (openapi-generatorではなく)
  2. security handlerの実装には、シンプルにOpenAPIのinitializeメソッドに引数securityHandlersを渡すのが良い。(openapi-security-handlerは、必要ない)

express-openapiを使おう (openapi-generatorではなく)

OpenAPI仕様のYAMLファイルを Swagger Editor (https://editor.swagger.io/) などを用いて作った後、openapi-generator (https://github.com/OpenAPITools/openapi-generator) を使ってスケルトンを作れそう...と思うのですが、openapi-generatorの出力するNode.js向けのスケルトンは、あまり良い感じではないです。

むしろexpress-openapi (https://www.npmjs.com/package/express-openapi) の方が、使う機能だけ使って書くように考えられているので、やりたいことに集中できるように思います。

security handlerの実装には、シンプルにOpenAPIのinitializeメソッドに引数securityHandlersを渡すのが良い。(openapi-security-handlerは、必要ない)

APIサーバを実装するとき、ほとんどの場合、セキュリティのことも考えることになると思います。

このとき、express-openapiのHighlightsを見ると、こういうことが記述されています。

Leverages security definitions for security management.
* See openapi-security-handler

openapi-security-handlerを使う必要があるのかな...と感じますが、必要ありません。

express-openapiでセキィリティハンドラを実装するときは、initializeメソッドの引数secuurityHandlersを渡すのが正解です。

initialize({
  apiDoc: apiDoc,
  app: app,
  securityHandlers: {
    keyScheme: function(req, scopes) {
      return Promise.resolve(true);
    }
  }
});

reqはexpressでおなじみのもので、scopesには、以下のようにAPIの定義のsecurityでスキーマ別に定義するスコープ配列が渡ってきます。

security:
- keyScheme: [admin]

セキュリティハンドラの戻り値は、即値でbooleanを返すか、booleanを返すPromiseとします。

trueが認証OKで、falseがNGです。

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1