@backstage/openapi-utils
Summary
This package is meant to provide a typed Express router for an OpenAPI spec. Based on the oatx library and adapted to override Express values.
Getting Started
Configuration
-
Run
yarn --cwd <package-dir> backstage-cli package schema openapi generateto translate yoursrc/schema/openapi.yamlto a new Typescript file insrc/schema/openapi.generated.ts. The command will try to execute both a lint and prettier step on the generated file, where applicable. -
In your plugin's
src/service/createRouter.ts,
import { ApiRouter } from `@backstage/backend-openapi-utils`;
import spec from '../schema/openapi.generated';
// ...
export function createRouter() {
const router = Router() as ApiRouter<typeof spec>;
// ...
return router;
}
Limitations
as constmakes all fieldsreadonlyTo ensure a good DX of using a simple imported JSON spec, we want to remove any type issues betweenreadonlyarrays and mutable arrays. Typescript does not allow them to be compared, so converting all imports from theopenapi3-tslibrary toreadonlyis important. This is achieved through theImmutableObjecttype intypes/immutable.ts.
...
// We want an interface like this,
Router() as ApiRouter<typeof spec>
// Not an interface like this,
Router() as ApiRouter<DeepWriteable<typeof spec>>
...
Future Work
Runtime validation
Using a package like express-openapi-validator, would allow us to remove validation of request bodies with AJV. However, AJV currently doesn't have support for OpenAPI 3.1 and express-openapi-validator enforces full URL matching for paths, meaning it cannot be mounted at the router level.