Gathering detailed insights and metrics for openapi-backend
Gathering detailed insights and metrics for openapi-backend
Gathering detailed insights and metrics for openapi-backend
Gathering detailed insights and metrics for openapi-backend
@backstage/backend-openapi-utils
OpenAPI typescript support.
@backstage/plugin-catalog-backend-module-openapi
A Backstage catalog backend module that helps with OpenAPI specifications
@backstage/plugin-catalog-backend-module-backstage-openapi
memory-card
ES6 Map like Async API, with Swagger API Backend Support.
Build, Validate, Route, Authenticate and Mock using OpenAPI
npm install openapi-backend
Typescript
Module System
Min. Node Version
Node Version
NPM Version
79.9
Supply Chain
98.5
Quality
80.8
Maintenance
100
Vulnerability
98.9
License
Updated on 03 Dec 2024
TypeScript (99.55%)
JavaScript (0.45%)
Cumulative downloads
Total Downloads
Last day
-4.4%
Compared to previous day
Last week
-15.1%
Compared to previous week
Last month
10.2%
Compared to previous month
Last year
56.7%
Compared to previous year
10
Build, Validate, Route, Authenticate, and Mock using OpenAPI definitions.
OpenAPI Backend is a Framework-agnostic middleware tool for building beautiful APIs with OpenAPI Specification.
New! OpenAPI Backend documentation is now found on openapistack.co
https://openapistack.co/docs/openapi-backend/intro
Full example projects included in the repo
npm install --save openapi-backend
1import OpenAPIBackend from 'openapi-backend'; 2 3// create api with your definition file or object 4const api = new OpenAPIBackend({ definition: './petstore.yml' }); 5 6// register your framework specific request handlers here 7api.register({ 8 getPets: (c, req, res) => res.status(200).json({ result: 'ok' }), 9 getPetById: (c, req, res) => res.status(200).json({ result: 'ok' }), 10 validationFail: (c, req, res) => res.status(400).json({ err: c.validation.errors }), 11 notFound: (c, req, res) => res.status(404).json({ err: 'not found' }), 12}); 13 14// initalize the backend 15api.init();
1import express from 'express'; 2 3const app = express(); 4app.use(express.json()); 5app.use((req, res) => api.handleRequest(req, req, res)); 6app.listen(9000);
See full Express TypeScript example
1// API Gateway Proxy handler 2module.exports.handler = (event, context) => 3 api.handleRequest( 4 { 5 method: event.httpMethod, 6 path: event.path, 7 query: event.queryStringParameters, 8 body: event.body, 9 headers: event.headers, 10 }, 11 event, 12 context, 13 );
See full Serverless Framework example
1module.exports = (context, req) => 2 api.handleRequest( 3 { 4 method: req.method, 5 path: req.params.path, 6 query: req.query, 7 body: req.body, 8 headers: req.headers, 9 }, 10 context, 11 req, 12 );
See full Azure Function example
1import fastify from 'fastify'; 2 3fastify.route({ 4 method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], 5 url: '/*', 6 handler: async (request, reply) => 7 api.handleRequest( 8 { 9 method: request.method, 10 path: request.url, 11 body: request.body, 12 query: request.query, 13 headers: request.headers, 14 }, 15 request, 16 reply, 17 ), 18}); 19fastify.listen();
1import Hapi from '@hapi/hapi'; 2 3const server = new Hapi.Server({ host: '0.0.0.0', port: 9000 }); 4server.route({ 5 method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], 6 path: '/{path*}', 7 handler: (req, h) => 8 api.handleRequest( 9 { 10 method: req.method, 11 path: req.path, 12 body: req.payload, 13 query: req.query, 14 headers: req.headers, 15 }, 16 req, 17 h, 18 ), 19}); 20server.start();
1import Koa from 'koa'; 2import bodyparser from 'koa-bodyparser'; 3 4const app = new Koa(); 5 6app.use(bodyparser()); 7app.use((ctx) => 8 api.handleRequest( 9 ctx.request, 10 ctx, 11 ), 12); 13app.listen(9000);
Handlers are registered for operationIds
found in the OpenAPI definitions. You can register handlers as shown above with new OpenAPIBackend()
constructor opts, or using the register()
method.
1async function getPetByIdHandler(c, req, res) { 2 const id = c.request.params.id; 3 const pet = await pets.getPetById(id); 4 return res.status(200).json({ result: pet }); 5} 6api.register('getPetById', getPetByIdHandler); 7// or 8api.register({ 9 getPetById: getPetByIdHandler, 10});
Operation handlers are passed a special Context object as the first argument, which contains the parsed request, the matched API operation and input validation results. The other arguments in the example above are Express-specific handler arguments.
The easiest way to enable request validation in your API is to register a validationFail
handler.
1function validationFailHandler(c, req, res) { 2 return res.status(400).json({ status: 400, err: c.validation.errors }); 3} 4api.register('validationFail', validationFailHandler);
Once registered, this handler gets called if any JSON Schemas in either operation parameters (in: path, query, header, cookie) or requestPayload don't match the request.
The context object c
gets a validation
property with the validation result.
OpenAPIBackend doesn't automatically perform response validation for your handlers, but you can register a
postResponseHandler
to add a response validation step using validateResponse
.
1api.register({ 2 getPets: (c) => { 3 // when a postResponseHandler is registered, your operation handlers' return value gets passed to context.response 4 return [{ id: 1, name: 'Garfield' }]; 5 }, 6 postResponseHandler: (c, req, res) => { 7 const valid = c.api.validateResponse(c.response, c.operation); 8 if (valid.errors) { 9 // response validation failed 10 return res.status(502).json({ status: 502, err: valid.errors }); 11 } 12 return res.status(200).json(c.response); 13 }, 14});
It's also possible to validate the response headers using validateResponseHeaders
.
1api.register({ 2 getPets: (c) => { 3 // when a postResponseHandler is registered, your operation handlers' return value gets passed to context.response 4 return [{ id: 1, name: 'Garfield' }]; 5 }, 6 postResponseHandler: (c, req, res) => { 7 const valid = c.api.validateResponseHeaders(res.headers, c.operation, { 8 statusCode: res.statusCode, 9 setMatchType: 'exact', 10 }); 11 if (valid.errors) { 12 // response validation failed 13 return res.status(502).json({ status: 502, err: valid.errors }); 14 } 15 return res.status(200).json(c.response); 16 }, 17});
If your OpenAPI definition contains Security Schemes you can register security handlers to handle authorization for your API:
1components: 2 securitySchemes: 3 - ApiKey: 4 type: apiKey 5 in: header 6 name: x-api-key 7security: 8 - ApiKey: []
1api.registerSecurityHandler('ApiKey', (c) => { 2 const authorized = c.request.headers['x-api-key'] === 'SuperSecretPassword123'; 3 // truthy return values are interpreted as auth success 4 // you can also add any auth information to the return value 5 return authorized; 6});
The authorization status and return values of each security handler can be accessed via the Context Object
You can also register an unauthorizedHandler
to handle unauthorized requests.
1api.register('unauthorizedHandler', (c, req, res) => { 2 return res.status(401).json({ err: 'unauthorized' }) 3});
See examples:
Mocking APIs just got really easy with OpenAPI Backend! Register a notImplemented
handler and use mockResponseForOperation()
to generate mock responses for operations with no custom handlers specified yet:
1api.register('notImplemented', (c, req, res) => { 2 const { status, mock } = c.api.mockResponseForOperation(c.operation.operationId); 3 return res.status(status).json(mock); 4});
OpenAPI Backend supports mocking responses using both OpenAPI example objects and JSON Schema:
1paths: 2 '/pets': 3 get: 4 operationId: getPets 5 summary: List pets 6 responses: 7 200: 8 $ref: '#/components/responses/PetListWithExample' 9 '/pets/{id}': 10 get: 11 operationId: getPetById 12 summary: Get pet by its id 13 responses: 14 200: 15 $ref: '#/components/responses/PetResponseWithSchema' 16components: 17 responses: 18 PetListWithExample: 19 description: List of pets 20 content: 21 'application/json': 22 example: 23 - id: 1 24 name: Garfield 25 - id: 2 26 name: Odie 27 PetResponseWithSchema: 28 description: A single pet 29 content: 30 'application/json': 31 schema: 32 type: object 33 properties: 34 id: 35 type: integer 36 minimum: 1 37 name: 38 type: string 39 example: Garfield
The example above will yield:
1api.mockResponseForOperation('getPets'); // => { status: 200, mock: [{ id: 1, name: 'Garfield' }, { id: 2, name: 'Odie' }]} 2api.mockResponseForOperation('getPetById'); // => { status: 200, mock: { id: 1, name: 'Garfield' }}
See full Mock API example on Express
For assistance with integrating openapi-backend in your company, reach out at support@openapistack.co.
OpenAPI Backend is Free and Open Source Software. Issues and pull requests are more than welcome!
No vulnerabilities found.
No security vulnerabilities found.