Koa + Open API Specification = Koas
Koas aims to make it easy to write a RESTful API based on Koa and an Open API V3 specification document. Koas is a middleware for Koa which implements the Open API V3 specification based on a plugin system.
Note: This is still unstable. Any breaking changes may be introduced until version 1.0.0 stable is released.
To install Koas along with all official plugins, run the following command:
koa koas-body-parser koas-core koas-operations koas-parameters koas-security koas-serializer koas-spec-handler koas-status-code koas-swagger-ui
The simplest way to use Koas, is to pull in this boilerplate:
const Koa = require('koa');
const { bodyParser } = require('koas-body-parser');
const { koas } = require('koas-core');
const { operations } = require('koas-operations');
const { parameters } = require('koas-parameters');
const { security } = require('koas-security');
const { serializer } = require('koas-serializer');
const { specHandler } = require('koas-spec-handler');
const { statusCode } = require('koas-status-code');
const { swaggerUI } = require('koas-swagger-ui');
const api = require('./api.json');
const controllers = require('./controllers');
const securityChecks = require('./securityChecks');
const app = new Koa();
app.use(
koas(api, [
// Serve the Open API document
specHandler(),
// Serve Swagger-UI
swaggerUI(),
// Verify authentication based on security requirements
security(securityChecks),
// Automatically set the success status code
statusCode(),
// Serialize the response body
serializer(),
// Parse path and query parameters
parameters(),
// Process the request body
bodyParser(),
// Run business logic
operations({ controllers }),
]),
);
app.listen(3333);
Koas only does a little work. The real functionality happens in plugins.
The Koas mono repository contains the following plugins:
koas-body-parser
koas-operations
koas-parameters
koas-security
koas-serializer
koas-spec-handler
koas-status-code
koas-swagger-ui
It is also possible to create your own plugins. A Koas plugin is simply a function which returns Koa middleware. It is recommended to create a function that returns a Koas plugin. This allows users to pass options to the plugin.
Koas provides TypeScript typings. All that’s needed to get typings for the entire plugin is a
Plugin
return type.
import { type Plugin } from 'koas-core';
export interface MyPluginOptions {
myOption: unknown;
}
export function myPlugin(options: MyPluginOptions): Plugin {
return ({ document, resolveRef, runAlways, validate }) =>
async (ctx, next) => {
await next();
};
}