### Koa App Setup with OpenAPI Router Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/koa-openapi/README.md This snippet demonstrates the setup of a Koa application using the Koa-OpenAPI router. It initializes the OpenAPI documentation, specifies service dependencies, defines the path to API definitions, and starts the server listening on port 3000. ```javascript const Koa = require('koa'); const Router = require('@koa/router'); const v1ApiDoc = require('./api-v1/openapi.json'); const v1WorldsService = require('./api-v1/service'); const app = new Koa(); const router = new Router(); router.openapi({ apiDoc: v1ApiDoc, dependencies: { worldsService: v1WorldsService }, paths: './api-v1/paths' }); app.use( router.routes() ); app.listen(3000); ``` -------------------------------- ### Define Main API Documentation (YAML) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/koa-openapi/README.md This snippet demonstrates defining the main OpenAPI documentation using a YAML string. It mirrors the JavaScript structure, providing an alternative for API specification. Dependencies: None. Output: A YAML string representing the OpenAPI specification. ```yaml # ./api-v1/api-doc.yml swagger: '2.0' basePath: '/v1' info: title: 'A getting started API.' version: '1.0.0' definitions: World: type: 'object' properties: name: description: 'The name of this world.' type: 'string' required: - 'name' paths: {} ``` -------------------------------- ### Express-OpenAPI Initialization with TypeScript Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Example of initializing express-openapi using TypeScript. It demonstrates importing necessary modules, setting up Express, and configuring `initialize` with path and route file configurations. ```typescript import * as express from "express"; import * as bodyParser from "body-parser"; import { initialize } from "express-openapi"; const app = express(); app.use(bodyParser.json()); initialize({ apiDoc: './api-doc.js', app, paths: './built/api-paths', routesGlob: '**/*.{ts,js}', routesIndexFileRegExp: /(?:index)?\.[tj]s$/ }); app.use(((err, req, res, next) => { res.status(err.status).json(err); }) as express.ErrorRequestHandler); app.listen(3000); ``` -------------------------------- ### Define Main API Documentation (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/koa-openapi/README.md This snippet shows how to define the main OpenAPI documentation for your API using JavaScript objects. It includes basic structure like swagger version, basePath, API info, definitions, and an empty paths object. Dependencies: None. Output: An object representing the OpenAPI specification. ```javascript const apiDoc = { swagger: '2.0', basePath: '/v1', info: { title: 'A getting started API.', version: '1.0.0' }, definitions: { World: { type: 'object', properties: { name: { description: 'The name of this world.', type: 'string' } }, required: ['name'] } }, paths: {} }; export default apiDoc; ``` -------------------------------- ### Initialize Koa Router with koa-openapi (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/koa-openapi/README.md This JavaScript code initializes a Koa application and its router using `koa-openapi`. It includes necessary middleware like `bodyParser` and imports the router, OpenAPI initialization function, service, and API documentation. Dependencies: `koa`, `koa-router`, `koa-bodyparser`, `koa-openapi`. Input: Koa app instance, router, service, and apiDoc. Output: Configured Koa application. ```javascript import Koa from 'koa'; import Router from 'koa-router'; import bodyParser from 'koa-bodyparser'; import { initialize } from 'koa-openapi'; import v1WorldsService from './api-v1/services/worldsService'; import v1ApiDoc from './api-v1/api-doc'; const app = new Koa(); const router = new Router(); app.use(bodyParser()); initialize({ router, ``` -------------------------------- ### Create Path Handler with Operation Definition (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/koa-openapi/README.md This JavaScript code defines a path handler for 'worlds' that includes a GET operation. It specifies the operation's summary, parameters, and responses using the `apiDoc` property, enabling `koa-openapi` to process it. Dependencies: `worldsService`. Input: `worldsService` instance. Output: An object containing operation functions. ```javascript // ./api-v1/paths/worlds.js export default function(worldsService) { let operations = { GET }; function GET(ctx, next) { ctx.status = 200; ctx.body = worldsService.getWorlds(req.query.worldName); } // NOTE: We could also use a YAML string here. GET.apiDoc = { summary: 'Returns worlds by name.', operationId: 'getWorlds', parameters: [ { in: 'query', name: 'worldName', required: true, type: 'string' } ], responses: { 200: { description: 'A list of worlds that match the requested name.', schema: { type: 'array', items: { $ref: '#/definitions/World' } } }, default: { description: 'An error occurred', schema: { additionalProperties: true } } } }; return operations; } ``` -------------------------------- ### Implement World Service (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/koa-openapi/README.md This JavaScript service provides functionality to retrieve world data. It exposes a `getWorlds` method that filters worlds based on a provided name. Dependencies: None. Input: World name (string). Output: An array of world objects. ```javascript // ./api-v1/services/worldsService.js let worlds = { Earth: { name: 'Earth' } }; const worldsService = { getWorlds(name) { return worlds[name] ? [worlds[name]] : []; } }; export default worldsService; ``` -------------------------------- ### Initialize Express App with express-openapi Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Initializes an Express application using the 'express-openapi' middleware. This setup typically involves importing necessary modules and configuring the middleware to integrate OpenAPI specifications with the Express routes. ```javascript import express from 'express'; import { initialize } from 'express-openapi'; // ... rest of the app setup ``` -------------------------------- ### Initialize Express OpenAPI Application Source: https://context7.com/kogosoftwarellc/open-api/llms.txt Bootstraps an Express application with OpenAPI routing, validation, and documentation. This setup integrates OpenAPI specifications (v2.0 and v3.0) into the routing and request/response lifecycle. ```APIDOC ## Initialize Express OpenAPI Application ### Description Bootstraps an Express application with OpenAPI routing, validation, and documentation. The framework handles automatic parameter validation, type coercion, default value assignment, response validation, and security enforcement based on OpenAPI schemas. ### Method `POST` (Implicitly handled by `initialize` function) ### Endpoint `/` (Root of the Express app, routes are defined by `paths` option) ### Parameters #### Query Parameters None #### Request Body None (Configuration is passed as an object to `initialize`) ### Request Example ```javascript const express = require('express'); const { initialize } = require('express-openapi'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.use(bodyParser.json()); // Initialize with file-based routing await initialize({ app: app, apiDoc: { swagger: '2.0', basePath: '/v1', info: { title: 'User Management API', version: '1.0.0' }, definitions: { User: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' }, email: { type: 'string', format: 'email' } }, required: ['name', 'email'] }, Error: { type: 'object', properties: { message: { type: 'string' }, code: { type: 'string' } } } }, paths: {} }, paths: path.resolve(__dirname, 'api-routes'), docsPath: '/api-docs', exposeApiDocs: true }); // Error handling middleware app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message, errors: err.errors }); }); app.listen(3000); ``` ### Response #### Success Response (Implicit) - The `initialize` function modifies the Express app to include OpenAPI routing and middleware. No direct response to the caller of `initialize`. #### Response Example N/A ``` -------------------------------- ### TypeScript Route Handler Example Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Defines parameters and operations for a TypeScript route handler using `express-openapi`. It includes defining path parameters, middleware, and operation-specific documentation using `GET.apiDoc` and `POST.apiDoc`. ```typescript import { Operation } from "express-openapi"; export const parameters = [ { in: 'path', name: 'id', required: true, type: 'integer' } ]; export const GET: Operation = [ /* business middleware not expressible by OpenAPI documentation goes here */ (req, res, next) => { res.status(200).json(/* return the user */); } ]; GET.apiDoc = { description: 'A description for retrieving a user.', tags: ['users'], operationId: 'getUser', // parameters for this operation parameters: [ { in: 'query', name: 'firstName', type: 'string' } ], responses: { default: { $ref: '#/definitions/Error' } } }; export const POST: Operation = (req, res, next) => { /* ... */ } POST.apiDoc = { /* ... */ }; ``` -------------------------------- ### Create API Path Handler (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md A path handler for the 'worlds' resource that exposes a GET operation. It defines the operation's metadata (summary, parameters, responses) in `apiDoc` and uses dependency injection for a 'worldsService'. ```javascript export default function(worldsService) { let operations = { GET }; function GET(req, res, next) { res.status(200).json(worldsService.getWorlds(req.query.worldName)); } GET.apiDoc = { summary: 'Returns worlds by name.', operationId: 'getWorlds', parameters: [ { in: 'query', name: 'worldName', required: true, type: 'string' } ], responses: { 200: { description: 'A list of worlds that match the requested name.', schema: { type: 'array', items: { $ref: '#/definitions/World' } } }, default: { description: 'An error occurred', schema: { additionalProperties: true } } } }; return operations; } ``` -------------------------------- ### Instantiate and Use OpenAPIDefaultSetter in TypeScript Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/openapi-default-setter/README.md Demonstrates how to instantiate the OpenAPIDefaultSetter with parameter definitions and then use its `handle` method to set default values on a request object. This example shows setting a default for a query parameter named 'foo'. ```typescript import OpenAPIDefaultSetter from 'openapi-default-setter'; const defaultSetter = new OpenAPIDefaultSetter({ parameters: [ { in: 'query', type: 'integer', name: 'foo', default: 5 } ] }); const request = {query: {} }; defaultSetter.handle(request); console.log(req.query.foo); //=> 5 ``` -------------------------------- ### Create Path Handler Module with Parameters and Operations in JavaScript Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Demonstrates how to create a route handler module that exports HTTP methods (GET, POST, etc.) with optional parameters and apiDoc specifications. Handlers can be simple functions or arrays of middleware followed by a handler function. ```javascript module.exports = { // parameters for all operations in this path parameters: [ { in: 'path', name: 'id', required: true, type: 'integer' } ], get: [ /* business middleware not expressible by OpenAPI documentation goes here */ function(req, res, next) { var validationError = res.validateResponse(200, /* return the user or an error */); if (validationError) return next(validationError); } res.status(200).json(/* return the user or an error */); } ], post: post }; module.exports.get.apiDoc = { description: 'A description for retrieving a user.', tags: ['users'], operationId: 'getUser', // parameters for this operation parameters: [ { in: 'query', name: 'firstName', type: 'string' } ], responses: { default: { $ref: '#/definitions/Error' } } }; function post(req, res, next) { /* ... */ } post.apiDoc = { /* ... */ }; ``` -------------------------------- ### GET /users/{id} Source: https://context7.com/kogosoftwarellc/open-api/llms.txt Retrieves a user by their unique ID. This endpoint demonstrates how to define path parameters and query parameters with inline OpenAPI documentation for a route handler. ```APIDOC ## GET /users/{id} ### Description Retrieve a user by ID. Parameters are validated and coerced automatically. Access to `apiDoc` and `operationDoc` is available via `req`. ### Method `GET` ### Endpoint `/users/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier for the user. #### Query Parameters - **includeProfile** (boolean) - Optional - Defaults to `false`. Include user profile information. #### Request Body None ### Request Example (No explicit request body for GET, but parameters are handled) ```http GET /v1/users/123?includeProfile=true ``` ### Response #### Success Response (200) - **id** (integer) - The user's unique identifier. - **name** (string) - The user's name. - **email** (string) - The user's email address. #### Response Example ```json { "id": 123, "name": "John Doe", "email": "john@example.com" } ``` ``` -------------------------------- ### Initialize OpenAPI Response Validator Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/openapi-response-validator/README.md Demonstrates how to initialize the OpenAPIResponseValidator with response schemas and definitions. This is the core setup for validating incoming API responses against expected structures. It requires 'responses' and can optionally take 'definitions' for schema references. ```javascript var OpenAPIResponseValidator = require('openapi-response-validator'); var responseValidator = new OpenAPIResponseValidator({ responses: { 200: { description: 'We found what you were looking for.', schema: { $ref: '#/definitions/ResourceResponse' } }, default: { description: 'Something happened...', schema: { $ref: '#/definitions/SomeErrorResponse' } } }, definitions: { ResourceResponse: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } }, required: ['id', 'name'] }, SomeErrorResponse: { type: 'object', properties: { errorCode: { type: 'string' }, message: { type: 'string' } } } } }); ``` -------------------------------- ### Initialize express-openapi with Consumes Middleware (Multer for File Uploads) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md This example shows how to configure `express-openapi` to handle `multipart/form-data` requests, typically used for file uploads. It utilizes the `multer` middleware to process file uploads and integrates it into the `consumesMiddleware` configuration. Non-file fields are available in `req.body`, and files are in `req.files`. ```javascript var multer = require('multer'); initialize({ /*...*/ consumesMiddleware: { 'multipart/form-data': function(req, res, next) { multer().any()(req, res, function(err) { if (err) return next(err); req.files.forEach(function(f) { req.body[f.fieldname] = ''; // Set to empty string to satisfy OpenAPI spec validation }); return next(); }); } } /*...*/ }); ``` -------------------------------- ### Define Express Route Handler with Path Parameters Source: https://context7.com/kogosoftwarellc/open-api/llms.txt Defines route handlers for Express with inline OpenAPI validation and documentation. This snippet demonstrates defining parameters, HTTP methods (GET, PUT, DELETE), and associated OpenAPI documentation for each. It shows how to access validated request parameters and use response validation. Dependencies include the initialized Express app from the previous step. ```javascript // api-routes/users/{id}.js module.exports = { parameters: [ { in: 'path', name: 'id', required: true, type: 'integer', description: 'User ID' } ], get: getUserById, put: updateUser, delete: deleteUser }; function getUserById(req, res, next) { // Parameters are already validated and coerced const userId = req.params.id; // Already an integer // Access to apiDoc and operationDoc console.log(req.apiDoc.basePath); // '/v1' console.log(req.operationDoc.operationId); // 'getUser' const user = { id: userId, name: 'John Doe', email: 'john@example.com' }; // Validate response before sending const validationError = res.validateResponse(200, user); if (validationError) { return next(validationError); } res.status(200).json(user); } getUserById.apiDoc = { description: 'Retrieve a user by ID', operationId: 'getUser', tags: ['users'], parameters: [ { in: 'query', name: 'includeProfile', type: 'boolean', default: false } ], responses: { 200: { description: 'User found', schema: { $ref: '#/definitions/User' } }, 404: { description: 'User not found', schema: { $ref: '#/definitions/Error' } }, default: { description: 'Unexpected error', schema: { $ref: '#/definitions/Error' } } } }; function updateUser(req, res) { const userId = req.params.id; const updatedUser = { ...req.body, id: userId }; res.status(200).json(updatedUser); } updateUser.apiDoc = { description: 'Update a user', operationId: 'updateUser', tags: ['users'], parameters: [ { in: 'body', name: 'user', required: true, schema: { $ref: '#/definitions/User' } } ], responses: { 200: { description: 'User updated', schema: { $ref: '#/definitions/User' } } } }; function deleteUser(req, res) { res.status(204).send(); } deleteUser.apiDoc = { description: 'Delete a user', operationId: 'deleteUser', tags: ['users'], responses: { 204: { description: 'User deleted successfully' } } }; ``` -------------------------------- ### Custom coercion strategy for OpenAPI request coercer (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/openapi-request-coercer/README.md Shows how to implement a custom coercion strategy for boolean, integer, and number types. This example defines a strategy where booleans are coerced based on 'true'/'false' (case-sensitive), integers are coerced only if even (otherwise null), and numbers leverage the default strategy. ```javascript import OpenapiRequestCoercer from 'openapi-request-coercer'; const coercionStrategy = { boolean: (input) => { if (typeof input === 'boolean') { return input; } if (input === 'false') { return false; } else if (input === 'true') { return true; } return input; }, number: (input) => { var result = Number(input); return isNaN(result) || (result%2) === 1 ? null : result; } }; const parameters = { /* ... */ }; const sut = new OpenapiRequestCoercer({ parameters, coercionStrategy }); const result = sut.coerce(request); ``` -------------------------------- ### Initialize Express OpenAPI with Services and Paths Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Sets up an Express application with OpenAPI configuration, including API documentation (YAML or object), service dependencies, and path definitions. The initialize function configures the routing and middleware stack, then the app listens on port 3000. Supports both inline apiDoc objects and external YAML file paths. ```javascript import v1WorldsService from './api-v1/services/worldsService'; import v1ApiDoc from './api-v1/api-doc'; const app = express(); initialize({ app, // NOTE: If using yaml you can provide a path relative to process.cwd() e.g. // apiDoc: './api-v1/api-doc.yml', apiDoc: v1ApiDoc, dependencies: { worldsService: v1WorldsService }, paths: './api-v1/paths' }); app.listen(3000); ``` -------------------------------- ### Initialize express-openapi with operations and dependencies Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Illustrates initializing express-openapi with an API document and defining operation handlers. It also shows how to inject dependencies, such as a logging function, into the operation handlers, which must be regular function expressions to access `this.dependencies`. ```javascript import express from 'express'; import { initialize } from 'express-openapi'; const app = express(); initialize({ app, apiDoc: './apiDoc.yml', operations: { getFoo: function(req, res) { res.send('foo'); } } }); app.listen(3000); ``` ```javascript import express from 'express'; import { initialize } from 'express-openapi'; const app = express(); initialize({ app, apiDoc: './apiDoc.yml', dependencies: { log: console.log }, operations: { getFoo: function(req, res) { this.dependencies.log('calling request handler'); res.send('foo'); } } }); app.listen(3000); ``` -------------------------------- ### Generate API Client via CLI (Shell) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/fetch-openapi/README.md Generates an API client JavaScript file using the `fetch-openapi` CLI tool. It takes the OpenAPI document URL or file path and an output path, with optional presets for different JavaScript environments. ```shell fetch-openapi --api-doc-url http://petstore.swagger.io/v2/swagger.json \ --output-file-path ./api.js \ --preset es6 ``` -------------------------------- ### Initialize Express OpenAPI Application Source: https://context7.com/kogosoftwarellc/open-api/llms.txt Initializes an Express application with OpenAPI routing, validation, and documentation using file-based routing. It requires 'express', 'express-openapi', and 'body-parser'. It takes an Express app instance, OpenAPI documentation object, and paths to route definitions as input. The output is a configured Express app ready to handle API requests according to the OpenAPI spec. ```javascript const express = require('express'); const { initialize } = require('express-openapi'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.use(bodyParser.json()); // Initialize with file-based routing await initialize({ app: app, apiDoc: { swagger: '2.0', basePath: '/v1', info: { title: 'User Management API', version: '1.0.0' }, definitions: { User: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' }, email: { type: 'string', format: 'email' } }, required: ['name', 'email'] }, Error: { type: 'object', properties: { message: { type: 'string' }, code: { type: 'string' } } } }, paths: {} }, paths: path.resolve(__dirname, 'api-routes'), docsPath: '/api-docs', exposeApiDocs: true }); // Error handling middleware app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message, errors: err.errors }); }); app.listen(3000); ``` -------------------------------- ### Initialize with Dependency Injection Source: https://context7.com/kogosoftwarellc/open-api/llms.txt Demonstrates how to initialize express-openapi and inject custom services and dependencies into route handlers. This allows for cleaner separation of concerns and testable code. ```APIDOC ## Initialize with Dependency Injection Injects services and dependencies into route handlers. ### Method POST ### Endpoint /initialize ### Parameters #### Request Body - **apiDoc** (object) - Required - The OpenAPI document. - **app** (object) - Required - The Express application instance. - **paths** (string) - Required - The path to the directory containing route files. - **dependencies** (object) - Optional - An object containing services to be injected into route handlers. ### Request Example ```javascript const express = require('express'); const { initialize } = require('express-openapi'); // Create backend services const userService = { getUser: (id) => ({ id, name: 'Jane Doe' }) }; const authService = { validateToken: (token) => ({ userId: 1, role: 'admin' }) }; const app = express(); await initialize({ apiDoc: require('./api-doc.js'), app: app, paths: './api-routes', dependencies: { userService: userService, authService: authService } }); ``` ### Response #### Success Response (200) - **message** (string) - Initialization successful. #### Response Example ```json { "message": "API initialization complete." } ``` ``` -------------------------------- ### Extend OpenAPI Schema with Custom Properties Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Uses the 'x-express-openapi-schema-extension' vendor extension to extend the schema validation capabilities. This example adds support for 'oneOf' in OpenAPI 2.0 documents, which is natively unsupported in that version. The extension defines custom schema properties that augment the validation behavior. ```json { "x-express-openapi-schema-extension": { "definitions": { "schema": { "properties": { "oneOf": { "type": "array", "minItems": 1, "items": { "$ref": "#/definitions/schema" } } } } } } } ``` -------------------------------- ### Initialize express-openapi with Consumes Middleware (Body Parser JSON) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md This code snippet demonstrates how to initialize the `express-openapi` library with custom `consumesMiddleware`. It specifically shows the configuration for handling `application/json` content types using `body-parser`. This allows the server to correctly parse JSON request bodies. ```javascript var bodyParser = require('body-parser'); initialize({ /*...*/ consumesMiddleware: { 'application/json': bodyParser.json(), 'text/text': bodyParser.text() } /*...*/ }); ``` -------------------------------- ### Express Middleware to Validate All Responses Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md This JavaScript middleware overrides `res.send` to perform response validation using `res.validateResponse`. It handles strict validation modes, logs warnings for validation errors, and returns a 500 error if validation fails in strict mode. This middleware is intended to be added to an Express application's setup. ```javascript function validateAllResponses(req, res, next) { const strictValidation = req.apiDoc['x-express-openapi-validation-strict'] ? true : false; if (typeof res.validateResponse === 'function') { const send = res.send; res.send = function expressOpenAPISend(...args) { const onlyWarn = !strictValidation; if (res.get('x-express-openapi-validation-error-for') !== undefined) { return send.apply(res, args); } const body = args[0]; let validation = res.validateResponse(res.statusCode, body); let validationMessage; if (validation === undefined) { validation = { message: undefined, errors: undefined }; } if (validation.errors) { const errorList = Array.from(validation.errors).map(_ => _.message).join(','); validationMessage = `Invalid response for status code ${res.statusCode}: ${errorList}`; console.warn(validationMessage); // Set to avoid a loop, and to provide the original status code res.set('x-express-openapi-validation-error-for', res.statusCode.toString()); } if (onlyWarn || !validation.errors) { return send.apply(res, args); } else { res.status(500); return res.json({ error: validationMessage }); } } } next(); } initialize({ app: app, paths: path.resolve(__dirname, 'api-paths'), apiDoc: { ...apiDoc, 'x-express-openapi-additional-middleware': [validateAllResponses], 'x-express-openapi-validation-strict': true } }); ``` -------------------------------- ### Define Main API Documentation (YAML) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md An alternative to the JavaScript definition, this YAML string represents the core OpenAPI 2.0 document for an API. It specifies version, base path, API info, data models, and an empty paths object. ```yaml swagger: '2.0' basePath: '/v1' info: title: 'A getting started API.' version: '1.0.0' definitions: World: type: 'object' properties: name: description: 'The name of this world.' type: 'string' required: - 'name' paths: {} ``` -------------------------------- ### Initialize OpenAPI Security Handler with Security Definitions Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/openapi-security-handler/README.md Creates an OpenAPISecurityHandler instance with security definitions, custom handlers for each scheme, and operation-level security requirements. The handler processes security schemes in parallel and resolves when any scheme combination succeeds. ```javascript import OpenAPISecurityHandler from 'openapi-security-handler'; const handler = new OpenAPISecurityHandler({ securityDefinitions: { keyScheme: { type: 'apiKey', name: 'api_key', in: 'header' }, passwordScheme: { type: 'basic' } }, securityHandlers: { keyScheme: function(req, scopes, securityDefinition) { req.user = {name: 'fred'}; return true; }, passwordScheme: function(req, scopes, securityDefinition) { req.user = {name: 'fred'}; return true; } }, operationSecurity: [ { keyScheme: ['write'] }, { passwordScheme: ['write'] } ] }); ``` -------------------------------- ### args.paths Configuration Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Configure the paths to your API route files or route specifications. Paths are logically structured according to their URL path, with support for both directory-based and module-based route definitions. Uses Swagger format for parameters (e.g., {id} instead of :id) for cross-platform compatibility. ```APIDOC ## Configuration: args.paths ### Description Defines the relative path or paths to directories containing route files or route specifications. ### Type String or Array ### Required Yes (unless args.operations is provided) ### Usage #### Directory-Based Routes For cross-platform compatibility, URLs accepting parameters use Swagger format `{id}` instead of Express format `:id`. **Example Directory Structure:** ``` paths/ users/ {id}.js users.js ``` **Corresponding API Endpoints:** - `GET /v1/users/{id}` - `POST /v1/users` #### Example Route File: paths/users/{id}.js ```javascript module.exports = { parameters: [ { in: 'path', name: 'id', required: true, type: 'integer' } ], get: [ function(req, res, next) { var validationError = res.validateResponse(200); if (validationError) return next(validationError); res.status(200).json(/* return user */); } ] }; module.exports.get.apiDoc = { description: 'Retrieve a user by ID.', tags: ['users'], operationId: 'getUser', parameters: [ { in: 'query', name: 'firstName', type: 'string' } ], responses: { default: { $ref: '#/definitions/Error' } } }; ``` #### Module-Based Routes Alternatively, specify route specifications with explicit path and module: ```javascript { path: '/foo/{id}', module: require('./handlers/foo') } ``` ### Method Definitions Methods can be either: - A single handler function - An array of middleware + handler function **Note:** Handlers in args.operations will override handlers in args.paths ``` -------------------------------- ### Generate API Client Programmatically (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/fetch-openapi/README.md Generates an API client JavaScript string using the `fetch-openapi` library programmatically. This involves requiring the library, loading the API document, and specifying options like the preset ('node' or 'es6'), then writing the generated code to a file. ```javascript var fs = require('fs'); var fetchOpenapi = require('fetch-openapi'); // See http://petstore.swagger.io/v2/swagger.json for an example API doc. var apiDoc = require('./petstore-api-doc.json'); var options = { preset: 'node' }; // generator is a string of javascript. var generator = fetchOpenApi(apiDoc, options); fs.writeFileSync('./petStore.js', generator, 'utf8'); // now we can use the client. var petStore = require('./petStore'); petStore.addPet({/* data */})// => handle the promise ``` -------------------------------- ### Create API Service (JavaScript) Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md A simple service implementation for managing 'worlds' data. It provides a `getWorlds` method that returns an array of worlds matching a given name, or an empty array if no match is found. ```javascript let worlds = { Earth: { name: 'Earth' } }; const worldsService = { getWorlds(name) { return worlds[name] ? [worlds[name]] : []; } }; export default worldsService; ``` -------------------------------- ### Initialize with Dependency Injection in Node.js Source: https://context7.com/kogosoftwarellc/open-api/llms.txt Injects services and dependencies into route handlers using express-openapi. It requires the 'express' and 'express-openapi' modules. The `initialize` function takes an `apiDoc`, `app`, `paths`, and a `dependencies` object containing the services to be injected. Route handlers then receive these services as arguments. ```javascript const express = require('express'); const { initialize } = require('express-openapi'); // Create backend services const userService = { getUser: (id) => ({ id, name: 'Jane Doe' }), createUser: (data) => ({ id: 123, ...data }), deleteUser: (id) => true }; const authService = { validateToken: (token) => ({ userId: 1, role: 'admin' }) }; const app = express(); await initialize({ apiDoc: require('./api-doc.js'), app: app, paths: './api-routes', dependencies: { userService: userService, authService: authService } }); // api-routes/users.js - receives injected dependencies module.exports = function(userService, authService) { return { GET: function(req, res) { // Use injected services const users = userService.getUser(req.params.id); res.status(200).json(users); } }; }; ``` -------------------------------- ### Initialize express-openapi with external schemas Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Demonstrates how to initialize the express-openapi library with external schemas for resolving $ref references. It shows mapping schema IDs to pre-loaded schema objects, which can then be used within the api-doc file for parameters and definitions. ```javascript initialize({ apiDoc: require('v3-api-doc'), /*...*/ externalSchemas: { 'http://example.com/schema': { description: "example schema", type: object, /*....*/ }, 'http://example.com/another-schema': { /*....*/ } } /*...*/ }); ``` ```javascript { /*...*/ parameters: { foo: { "in": "body", name: "foo", schema: { $ref: 'http://example.com/schema'} } }, /*...*/ definitions: { bar: { $ref: 'http://example.com/another-schema#/definitions/bar'} } } ``` ```javascript put.apiDoc = { /*...*/ parameters: [ { "in": "body", name: "foo", schema: { $ref: 'http://example.com/schema'} } ], /*...*/ } ``` -------------------------------- ### Initialize Koa OpenAPI Application Source: https://context7.com/kogosoftwarellc/open-api/llms.txt This snippet demonstrates how to initialize a Koa application with OpenAPI routing and validation using the 'koa-openapi' library. It sets up routing, request body parsing, and dependency injection for API routes. Dependencies include 'koa', 'koa-router', 'koa-bodyparser', and 'koa-openapi'. ```javascript const Koa = require('koa'); const Router = require('koa-router'); const bodyParser = require('koa-bodyparser'); const { initialize } = require('koa-openapi'); const app = new Koa(); const router = new Router(); app.use(bodyParser()); await initialize({ router: router, apiDoc: { swagger: '2.0', basePath: '/v1', info: { title: 'Koa OpenAPI', version: '1.0.0' }, definitions: { User: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } }, required: ['name'] } }, paths: {} }, paths: './api-routes', dependencies: { userService: { getUsers: () => [{ id: 1, name: 'Alice' }], getUser: (id) => ({ id, name: 'Bob' }) } } }); app.use(router.routes()); app.use(router.allowedMethods()); app.listen(3000); // api-routes/users.js module.exports = function(userService) { return { GET: getUsers }; async function getUsers(ctx, next) { const users = await userService.getUsers(); ctx.status = 200; ctx.body = users; } getUsers.apiDoc = { description: 'List all users', operationId: 'listUsers', parameters: [], responses: { 200: { description: 'List of users', schema: { type: 'array', items: { $ref: '#/definitions/User' } } } } }; }; ``` -------------------------------- ### Import and use fs-routes to generate routes Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/fs-routes/README.md Demonstrates how to import the fs-routes module with TypeScript types and call it with a directory path to generate an array of route objects. The function scans the specified directory and returns FsRoute objects containing file paths and corresponding route patterns. ```TypeScript import fsRoutes, { FsRoute } from 'fs-routes'; const output: FsRoute[] = fsRoutes('routes'); ``` -------------------------------- ### args.promiseMode Configuration Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Enable promise support to allow middleware and path handlers to return promises. Supports both async/await (Node >= 7.6) and traditional promise chains for error handling and asynchronous operations. ```APIDOC ## Configuration: args.promiseMode ### Description Allows middleware and path handlers to return promises for asynchronous operations. ### Type Boolean ### Required No ### Default Value false ### Usage When enabled, handlers can use async/await or return promises directly. #### Example: Async/Await (Node >= 7.6) ```javascript export default function(worldsService) { const operations = { GET }; async function GET(req, res) { const worlds = await worldsService.getWorlds(req.query.worldName); if (!worlds.length) { throw { status: 404, message: 'No worlds were found' }; } res.status(200).json(worlds); } return operations; } ``` #### Example: Promise Chain (Node < 7.6) ```javascript function PUT(req, res) { return worldsService.getWorlds(req.query.worldName) .then(function(worlds) { if (!worlds.length) { throw { status: 404, message: 'No worlds were found' }; } res.status(200).json(worlds); }); } ``` ### Error Handling Errors can be thrown directly in async functions or rejected promises, and will be caught by the framework's error handling middleware. ``` -------------------------------- ### Define Path Directory Structure for Express OpenAPI Routes Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Shows the recommended directory layout for organizing route files according to URL paths. Uses swagger format for path parameters ({id}) instead of express format (:id) for cross-platform compatibility. ```text `paths/ `users/ `{id}.js users.js ``` -------------------------------- ### args.routesGlob Configuration Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Specify a glob pattern to control which file extensions are recognized as route files. Allows customization of file discovery patterns beyond the default JavaScript files. ```APIDOC ## Configuration: args.routesGlob ### Description Glob pattern to specify which files are recognized as route files. ### Type String ### Required No ### Default Value `**/*.js` ### Usage Modify the glob pattern to support different file extensions: ```javascript initialize({ apiDoc: apiDoc, app: app, paths: './api-v1/paths', routesGlob: '**/*.{js,ts}' }) ``` This example allows both JavaScript and TypeScript files to be recognized as route definitions. ``` -------------------------------- ### fs-routes output structure Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/fs-routes/README.md Shows the typical output format of fs-routes when processing a directory structure. Each route object contains the absolute file path and the derived route pattern, supporting dynamic route parameters like :id for nested resources. ```JavaScript var output = [ { path: '/my/project/path/routes/home.js', route: '/home' }, { path: '/my/project/path/routes/users/:id.js', route: '/users/:id' }, { path: '/my/project/path/routes/users/index.js', route: '/users/' } ]; ``` -------------------------------- ### args.routesIndexFileRegExp Configuration Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Define a custom regular expression pattern to identify index files. Allows flexibility in naming conventions for index files beyond the default `index.js` naming. ```APIDOC ## Configuration: args.routesIndexFileRegExp ### Description Regular expression pattern to identify index files in the routes directory. ### Type RegExp ### Required No ### Default Value `/(?:index)?\.js$/` ### Usage Customize the index file naming pattern: ```javascript initialize({ apiDoc: apiDoc, app: app, paths: './api-v1/paths', routesIndexFileRegExp: /(?:index|root)?\.js$/ }) ``` This example allows both `index.js` and `root.js` files to be treated as index files. ``` -------------------------------- ### Configure Security Handlers Source: https://context7.com/kogosoftwarellc/open-api/llms.txt Shows how to configure custom security handlers for authentication and authorization based on OpenAPI security definitions. Supports various schemes like API key and Basic Auth. ```APIDOC ## Configure Security Handlers Implements authentication and authorization with OpenAPI security definitions. ### Method POST ### Endpoint /configure-security ### Parameters #### Request Body - **app** (object) - Required - The Express application instance. - **apiDoc** (object) - Required - The OpenAPI document including `securityDefinitions`. - **paths** (string) - Required - The path to the directory containing route files. - **securityHandlers** (object) - Required - An object mapping security definition names to handler functions. ### Request Example ```javascript const { initialize } = require('express-openapi'); await initialize({ app: app, apiDoc: { swagger: '2.0', basePath: '/v1', info: { title: 'API', version: '1.0.0' }, securityDefinitions: { apiKey: { type: 'apiKey', name: 'X-API-Key', in: 'header' }, basicAuth: { type: 'basic' } }, paths: {} }, paths: './api-routes', securityHandlers: { apiKey: function(req, scopes, definition) { // ... implementation for API key validation ... return Promise.resolve(true); }, basicAuth: function(req, scopes, definition) { // ... implementation for Basic Auth validation ... return Promise.resolve(true); } } }); // api-routes/protected.js module.exports = { POST: function(req, res) { res.json({ message: `Hello ${req.user.username}` }); } }; module.exports.POST.apiDoc = { description: 'Protected endpoint', operationId: 'protectedOperation', security: [ { apiKey: [] }, { basicAuth: [] } // Falls back to basicAuth if apiKey fails ], responses: { 200: { description: 'Success', schema: { type: 'object' } } } }; ``` ### Response #### Success Response (200) - **message** (string) - Security handlers configured successfully. #### Response Example ```json { "message": "Security handlers configured." } ``` ``` -------------------------------- ### Initialize express-openapi with path security Source: https://github.com/kogosoftwarellc/open-api/blob/main/packages/express-openapi/README.md Shows how to configure path-specific security definitions for routes in express-openapi. It uses an array of tuples, where each tuple contains a RegExp to match paths and a security definition. The configuration allows for overriding or adding security to operations. ```javascript initialize({ apiDoc: require('v3-api-doc'), /*...*/ pathSecurity: [ // here /some/{pathId} will get theirSecurity. [/^\/some\/\{pathId\}/, [{mySecurity:[]}]], [/^\/some\/\{pathId\}/, [{theirSecurity:[]}]] ] /*...*/ }); ```