Builds an express-compatible router using OpenAPI
with request and response validation.
- Your
ExpressJS
server includesbody-parser
andcookie-parser
when applicable. - Your
OpenAPI
document is version3.0
and valid (See https://editor.swagger.io/). - Your
OpenAPI
document consumesapplication/json
and producesapplication/json
. - Your
OpenAPI
document operations declare anoperationId
.
Install express-openapi-json
:
npm install express-openapi-json
Create a router with one operation for the specified operationId
:
const router = api.createCore(require('./openapi.json'))
.operation('getUserById', ctx => api.json({id: ctx.query.id})))
.router();
Create a router with one controller (using decorators
):
class PersonController {
@api.createOperation('getUser')
get(context) {
return api.json({id: context.query.id});
}
}
const router = api.createCore(require('./openapi.json'))
.controller(new PersonController())
.router();
Using the router in express
:
app.use(router.express());
Using the router in express
mounted under /api
:
app.use('/api', router.express());
import api from 'express-openapi-json';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import express from 'express';
class UserController {
@api.createOperation('getUser')
get(context) {
return api.json({id: context.query.id});
}
@api.createOperation('postUser')
post(context) {
return api.status(200);
}
}
const router = api.createCore(require('./openapi.json'))
.controller(new UserController())
.router();
const server = express();
server.use(bodyParser.json());
server.use(cookieParser());
server.use(router.express());
server.listen(3000);
Certain scripts are made available after package installation.
Converts an openapi
document to TypeScript
definitions. Limitations:
- Your
OpenAPI
document must be stored asjson
.
Installation:
npm install json-schema-to-typescript --save-dev
Usage:
openapi2js your_openapi.json > your_typescript.ts
This section describes the supported features and limitations.
{
paths: {
[Path]: {
[method]: Operation = {
parameters?: Parameter[],
requestBody?: RequestBody
responses: {
[responseKey]: Response
}
}
}
}
}
Supported.
Supported with validation (including required
). Limitations:
- Parameter MUST have a
schema
or$ref
. See Schema. - Parameter MUST have a
schema.type
that is a primitive:boolean
(/^(1|0|true|false|yes|no)$/i
)integer
(/^[0-9]+$/
)number
(/^[0-9]+(\.[0-9]+)?$/
)string
Supported with validation. Limitations:
- Content MUST have a
contentType
=application/json
. - Content MUST have a
schema
forapplication/json
. See Schema.
Supported. See Components.
{
components: {
responses?: {
[responseName]: Response = {
headers?: Headers
content?: Content
}
}
schemas?: {
[schemaName]: Schema
}
}
}
Unsupported.
Supported with validation. Limitations:
- Content SHOULD have a
contentType
=application/json
. - Content MUST have a
schema
forapplication/json
. See Schema.