{"id":15102807,"url":"https://github.com/oaijs/koa-oai-router","last_synced_at":"2025-09-27T00:31:36.107Z","repository":{"id":42114970,"uuid":"75414661","full_name":"oaijs/koa-oai-router","owner":"oaijs","description":"Koa Router, based on OpenAPI, Swagger and Json Schema.","archived":true,"fork":false,"pushed_at":"2022-12-07T07:49:06.000Z","size":2837,"stargazers_count":104,"open_issues_count":8,"forks_count":15,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-09-13T07:12:24.857Z","etag":null,"topics":["jsonschema","koa","koa-oai-router","koa-router","oai","openapi","swagger"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/oaijs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-12-02T17:00:55.000Z","updated_at":"2025-02-26T06:22:35.000Z","dependencies_parsed_at":"2023-01-24T14:00:30.437Z","dependency_job_id":null,"html_url":"https://github.com/oaijs/koa-oai-router","commit_stats":null,"previous_names":["bitebit/koa-oai-router","amazing-gao/koa-oai-router"],"tags_count":14,"template":false,"template_full_name":null,"purl":"pkg:github/oaijs/koa-oai-router","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oaijs%2Fkoa-oai-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oaijs%2Fkoa-oai-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oaijs%2Fkoa-oai-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oaijs%2Fkoa-oai-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/oaijs","download_url":"https://codeload.github.com/oaijs/koa-oai-router/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oaijs%2Fkoa-oai-router/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":276033070,"owners_count":25573474,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-20T02:00:10.207Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["jsonschema","koa","koa-oai-router","koa-router","oai","openapi","swagger"],"created_at":"2024-09-25T19:07:15.012Z","updated_at":"2025-09-27T00:31:35.739Z","avatar_url":"https://github.com/oaijs.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Koa-OAI-Router\n\n[![License][license-img]][license-url]\n[![Node Version][node-image]][node-url]\n[![NPM Version][npm-img]][npm-url]\n[![Build Status][travis-img]][travis-url]\n[![Test Coverage][coveralls-img]][coveralls-url]\n[![Downloads][downloads-image]][downloads-url]\n[![Dependency Status][david-img]][david-url]\n\n[travis-img]: https://github.com/amazing-gao/koa-oai-router/workflows/Node.js%20CI/badge.svg\n[travis-url]: https://github.com/amazing-gao/koa-oai-router/actions\n[coveralls-img]: https://coveralls.io/repos/github/amazing-gao/koa-oai-router/badge.svg?branch=master\n[coveralls-url]: https://coveralls.io/github/amazing-gao/koa-oai-router?branch=master\n[npm-img]: https://img.shields.io/npm/v/koa-oai-router.svg\n[npm-url]: https://npmjs.org/package/koa-oai-router\n[david-img]: https://img.shields.io/david/amazing-gao/koa-oai-router.svg\n[david-url]: https://david-dm.org/amazing-gao/koa-oai-router\n[downloads-image]: https://img.shields.io/npm/dm/koa-oai-router.svg\n[downloads-url]: https://npmjs.org/package/koa-oai-router\n[license-img]: http://img.shields.io/badge/license-MIT-green.svg\n[license-url]: http://opensource.org/licenses/MIT\n[node-image]: https://img.shields.io/badge/node.js-v6.0.0-blue.svg\n[node-url]: http://nodejs.org/download/\n[koa-router]: https://github.com/alexmingoia/koa-router\n[oai]: https://github.com/OAI/OpenAPI-Specification\n[swagger]: http://swagger.io\n[swagger-ui]: http://swagger.io/swagger-ui\n[jsonschema]: http://json-schema.org\n[oai-paths]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathsObject\n[oai-definitions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#definitionsObject\n[oai-router-middleware]: https://github.com/oaijs/koa-oai-router-middleware\n[oai-router-parameters]: https://github.com/oaijs/koa-oai-router-parameters\n[oai-router-responses]: https://github.com/oaijs/koa-oai-router-responses\n[oai-router-correction]: https://github.com/oaijs/koa-oai-router-correction\n[oai-router-cache]: https://github.com/oaijs/koa-oai-router-cache\n[oai-router-rbac]: https://github.com/oaijs/koa-oai-router-rbac\n[oai-router-controller-mongo]: https://github.com/oaijs/koa-oai-router-controller-mongo\n[oai-router-examples]: https://github.com/oaijs/koa-oai-router-examples\n[migration]: ./docs/en/migration.md\n[usage-guides]: ./docs/en/usage-guides.md\n[references]: ./docs/en/references.md\n[api-explorer-img]: ./docs/api-explorer.png?raw=true\n\n[中文](./README.zh-CN.md)    [English](./README.md)\n\nI have used markdown and wiki to manage api doc, from which I have suffered a lot. It wastes too much time and is very boring. The document should be repaired when you change the api. It's very unconvenient to test and debug. The management of api doc totally depends on people. As a result, it is hard to make document have high quality. Meanwhile, the developers will spend more time on testing, which may have a bad effect on project. What's worse, it will affect our mood, which is unbearable for me : (\n\nSo I try my best to solve this problem. When there is a will, there is a way. Finally, I find The [OpenAPI Specification][oai]. And its ecological circle is perfect. [Swagger][swagger] includes lots of tool chain. According to the Specification, [Swagger UI][swagger-ui] can produce the document. The data types and models of OpenAPI are based on the [JSON-Schema Draft 4][jsonschema].\n\nI truly hope that this library can help those who are in the same trouble. Happy coding.\n\nBTW，PR \u0026 Issue \u0026 Star are welcome! : )\n\n---\n\n\u003c!-- @import \"[TOC]\" {cmd=\"toc\" depthFrom=1 depthTo=6 orderedList=false} --\u003e\n\u003c!-- code_chunk_output --\u003e\n\n- [Koa-OAI-Router](#koa-oai-router)\n- [Features](#features)\n- [Migration](#migration)\n- [Installation](#installation)\n- [Getting Started](#getting-started)\n  - [Creating web server](#creating-web-server)\n  - [Creating business middleware](#creating-business-middleware)\n  - [Creating api doc](#creating-api-doc)\n    - [Writing api base info](#writing-api-base-info)\n    - [Writing `paths` info](#writing-paths-info)\n    - [Writing `definitions` info](#writing-definitions-info)\n  - [Enjoying api-explorer](#enjoying-api-explorer)\n- [Documentation](#documentation)\n- [Ecosystem](#ecosystem)\n- [Plan](#plan)\n\n\u003c!-- /code_chunk_output --\u003e\n\n---\n\n# Features\n* Built-in Swagger-UI, easy to view and debug\n* Support OpenAPI/Swagger2.0 specification with yaml or json file\n* More friendly and convenient api doc splitting solution\n* Plugin system. Middleware loader, form validator, response handler, error handler supported as plugin\n* Inherit from [Koa-Router][koa-router], maintain the original function, features and performance\n\n# Migration\nIf you are not a 1.x user, please skip this section directly.\nIf you are a 1.x user and want to upgrade to version 2.0, I'm sorry that you will not upgrade to version 2.0 easily. Please read this [Migration][migration] carefully and follow the operation manual to upgrade.\n\n# Installation\n```sh\n# required koa 2.x\n\u003e npm install koa-oai-router --save\n```\n\n# Getting Started\nThe following will teach you how to use the router to build a web server with a good organizational structure and `api-explorer`.\n\nIn this case, it basically covers all the key points of the router, including:\n* configure router\n* configure plugin\n* mount plugin to router\n* mount router to app\n* write api doc\n* use plugin\n* enjoy api-explorer\n\nour target is:\n* to create a REST API Server\n* to implement a pets query api and return the array of pets found\n* to implement a creating api for pets and return the pet and id\n* to generate api documentation and enjoy api-explorer\n\nHere we go.\n\n## Creating web server\n```javascript\n// ./app.js\n\nconst Koa = require('koa');\nconst logger = require('koa-logger');\nconst bodyParser = require('koa-bodyparser');\nconst Router = require('koa-oai-router');\nconst middleware = require('koa-oai-router-middleware');\n\nconst app = new Koa();\n\n// *configure router - load api doc from directory api\nconst router = new Router({\n  apiDoc: './api',\n});\n\n// *configure plugin - identify x-oai-middleware in the api file and load the appropriate middleware from controllers\n// *mount plugin to router\nrouter.mount(middleware, './controllers');\n\napp.use(logger());\napp.use(bodyParser());\n// *mount router to app\napp.use(router.routes());\n\napp.listen(3000);\n```\n\n## Creating business middleware\nCreate business middleware directory `controllers` and write business middleware.\n```js\n// ./controllers/pets.js\n\nconst database = [];\n\n// Query pets in the database according to tags, and limit the query result according to the limit.\nasync function get(ctx, next) {\n  const { tags = '', limit = 999 } = ctx.request.query;\n  const tagsArray = tags.split(',');\n  const docs = [];\n\n  database.forEach((item, idx) =\u003e {\n    if (tagsArray.indexOf(item.tag) !== -1 \u0026\u0026 docs.length \u003c limit) {\n      item.id = idx + 1;\n      docs.push(item);\n    }\n  });\n\n  ctx.response.body = docs;\n}\n\n// Create a pet store to the database.\nasync function post(ctx, next) {\n  const body = ctx.request.body;\n\n  database.push(body);\n\n  ctx.response.body = {\n    id: database.length,\n    name: body.name,\n    tag: body.tag,\n  };\n}\n\nmodule.exports = {\n  get,\n  post,\n};\n```\n\n## Creating api doc\nIf you know nothing about [OpenAPI][oai], please read [OpenAPI][oai] carefully.\n\n### Writing api base info\nYou can describe the basic information of the service, such as the version of the service, the basic path, transmission protocol, author and permission license.\n```yaml\n# ./api/api.yaml\n\nswagger: '2.0'\ninfo:\n  version: 1.0.0\n  title: Swagger Petstore\n  description: \u003e-\n    A sample API that uses a petstore as an example to demonstrate features in\n    the swagger-2.0 specification\n  termsOfService: 'http://swagger.io/terms/'\n  contact:\n    name: Swagger API Team\n  license:\n    name: MIT\nbasePath: /api\nschemes:\n  - http\nconsumes:\n  - application/json\nproduces:\n  - application/json\n```\n\n### Writing `paths` info\nHolds the relative paths to the individual endpoints. The path is appended to the basePath in order to construct the full URL. Please refer to [Paths][oai-paths].\n\n```yaml\n# ./api/paths/pets.yaml\n\n/pets:\n  get:\n    description: \"Returns all pets from the system that the user has access to\"\n    operationId: \"findPets\"\n    produces:\n      - \"application/json\"\n    tags:\n      - pets\n    x-oai-middleware:\n      - file: pets\n        handler: get\n    parameters:\n      - name: \"tags\"\n        in: \"query\"\n        description: \"tags to filter by\"\n        required: false\n        type: \"array\"\n        items:\n          type: \"string\"\n        collectionFormat: \"csv\"\n      - name: \"limit\"\n        in: \"query\"\n        description: \"maximum number of results to return\"\n        required: false\n        type: \"integer\"\n        format: \"int32\"\n    responses:\n      \"200\":\n        description: \"pet response\"\n        schema:\n          type: \"array\"\n          items:\n            $ref: \"#/definitions/Pet\"\n      default:\n        description: \"unexpected error\"\n        schema:\n          $ref: \"#/definitions/ErrorModel\"\n  post:\n    description: \"Creates a new pet in the store.  Duplicates are allowed\"\n    operationId: \"addPet\"\n    produces:\n      - \"application/json\"\n    tags:\n      - pets\n    x-oai-middleware:\n      - file: pets\n        handler: post\n    parameters:\n      - name: \"pet\"\n        in: \"body\"\n        description: \"Pet to add to the store\"\n        required: true\n        schema:\n          $ref: \"#/definitions/NewPet\"\n    responses:\n      \"200\":\n        description: \"pet response\"\n        schema:\n          $ref: \"#/definitions/Pet\"\n      default:\n        description: \"unexpected error\"\n        schema:\n          $ref: \"#/definitions/ErrorModel\"\n```\n\n### Writing `definitions` info\nYou can define an object to hold data types that can be consumed and produced by operations. These data types can be primitives, arrays or models. Please refer to [Definitions][oai-definitions].\n\n1.Define interface error response data model `ErrorModel`.\n```yaml\n# ./api/definitions/error.yaml\n\nErrorModel:\n  type: \"object\"\n  required:\n    - \"code\"\n    - \"message\"\n  properties:\n    code:\n      type: \"integer\"\n      format: \"int32\"\n    message:\n      type: \"string\"\n```\n\n2.Define query success response data model `Pet`, define new request data model `NewPet`.\n```yaml\n# ./api/definitions/pets.yaml\n\nPet:\n  type: \"object\"\n  allOf:\n    - $ref: \"#/definitions/NewPet\"\n    - required:\n        - \"id\"\n      properties:\n        id:\n          type: \"integer\"\n          format: \"int64\"\n\nNewPet:\n  type: \"object\"\n  required:\n    - \"name\"\n  properties:\n    name:\n      type: \"string\"\n    tag:\n      type: \"string\"\n```\n\n## Enjoying api-explorer\nStart WEB service, test interface and enjoy api-explorer.\n\n```bash\n\u003e node app.js\n\u003e\n\u003e curl -X POST \"http://localhost:3000/api/pets\" -H \"Content-Type: application/json\" -d \"{ \\\"name\\\": \\\"luck\\\", \\\"tag\\\": \\\"dog\\\"}\"\n\u003e {\"id\":1,\"name\":\"luck\",\"tag\":\"dog\"}\n\u003e\n\u003e curl -X POST \"http://localhost:3000/api/pets\" -H \"Content-Type: application/json\" -d \"{ \\\"name\\\": \\\"lily\\\", \\\"tag\\\": \\\"cat\\\"}\"\n\u003e {\"id\":2,\"name\":\"lily\",\"tag\":\"cat\"}\n\u003e\n\u003e curl -X POST \"http://localhost:3000/api/pets\" -H \"Content-Type: application/json\" -d \"{ \\\"name\\\": \\\"mike\\\", \\\"tag\\\": \\\"dog\\\"}\"\n\u003e {\"id\":3,\"name\":\"mike\",\"tag\":\"dog\"}\n\u003e\n\u003e curl -X GET \"http://localhost:3000/api/pets?tags=cat,dog\u0026limit=2\"\n\u003e [{\"name\":\"luck\",\"tag\":\"dog\",\"id\":1},{\"name\":\"lily\",\"tag\":\"cat\",\"id\":2}]\n\n```\nAs you can see, all of the business middleware we wrote has been called normally.\nUse a browser to open `http://localhost:3000/api-explorer`, and you can enjoy api-explorer now.\n![Api Explorer][api-explorer-img]\n\n# Documentation\n* [Usage Guides][usage-guides]\n* [References  ][references]\n* [Migration   ][migration]\n* [Examples    ][oai-router-examples]\n\n# Ecosystem\n\n| name                                                           | description         | status     |\n| -------------------------------------------------------------- | ------------------- | ---------- |\n| [koa-oai-router-middleware][oai-router-middleware]             | middleware loader   | Done       |\n| [koa-oai-router-correction][oai-router-correction]             | form correction     | Done       |\n| [koa-oai-router-parameters][oai-router-parameters]             | form validator      | Done       |\n| [koa-oai-router-responses][oai-router-responses]               | response handler    | Done       |\n| [koa-oai-router-cache][oai-router-cache]                       | request cache       | Done       |\n| [koa-oai-router-rbac][oai-router-rbac]                         | request rbac        | Planning   |\n| [koa-oai-router-controller-mongo][oai-router-controller-mongo] | MongoDB REST server | Developing |\n\n# Plan\n* Support OpenAPI/Swagger3.0\n* More plugins\n* More unit tests\n* Benchmark\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foaijs%2Fkoa-oai-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Foaijs%2Fkoa-oai-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foaijs%2Fkoa-oai-router/lists"}