https://github.com/eropple/fastify-openapi3
Developer-friendly OpenAPI3 tooling for Fastify that's easy to use.
https://github.com/eropple/fastify-openapi3
fastify fastify-plugin json-schema openapi3 typescript
Last synced: 8 days ago
JSON representation
Developer-friendly OpenAPI3 tooling for Fastify that's easy to use.
- Host: GitHub
- URL: https://github.com/eropple/fastify-openapi3
- Owner: eropple
- Created: 2022-02-14T05:24:29.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2026-01-15T18:14:16.000Z (28 days ago)
- Last Synced: 2026-01-15T20:49:13.473Z (28 days ago)
- Topics: fastify, fastify-plugin, json-schema, openapi3, typescript
- Language: TypeScript
- Homepage:
- Size: 550 KB
- Stars: 26
- Watchers: 3
- Forks: 3
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# `@eropple/fastify-openapi3` #
_Because I just can't stop making OpenAPI libraries, I guess._
[](https://www.npmjs.com/package/@eropple/fastify-openapi3) [](https://github.com/eropple/fastify-openapi3/actions/workflows/ci.yaml)
## What is it? ##
This is a library to help you generate [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0)-compliant (or 3.0.3 if you do a little work on your own) specs from your [Fastify](https://www.fastify.io/) app. Others exist, but to my mind don't scratch the itch that the best OAS tooling does: making it faster and easier to create correct specs and valid API clients from those specs. Because of my [own](https://github.com/modern-project/modern-ruby) [background](https://github.com/eropple/nestjs-openapi3) in building OpenAPI libraries, and my growing appreciation for Fastify, I decided to take a crack at it.
This library presupposes that you use [`@sinclair/typebox`](https://github.com/sinclairzx81/typebox) to define the JSON schema used in your requests, and from that JSON Schema derives types. (Ergonomics for non-TypeScript users is specifically out-of-scope.) It will walk all your routes, determine your schema, and extract and deduplicate those schemas to present a relatively clean and easy-to-use OpenAPI document. It'll then also serve JSON and YAML versions of your specification, as well as host an interactive API explorer with try-it-out features courtesy of [Rapidoc](https://mrin9.github.io/RapiDoc/) or [Scalar](https://scalar.com).
**Fair warning:** This library is in Early Access(tm) and while the functionality that's here does work, there's some functionality that _doesn't_ exist. The stuff that stands out to me personally can be found in [TODO.md](https://github.com/eropple/fastify-openapi3/blob/main/TODO.md), including a short list of things this plugin _won't_ do.
## Usage ##
First, install it, etc. etc.:
```bash
npm install @eropple/fastify-openapi3
pnpm add @eropple/fastify-openapi3
yarn add @eropple/fastify-openapi3
```
Once you've installed it--well, you'd best go do some things to set it up, huh? There's a manual test (originally added to smoke out issues with Rapidoc serving) in [`examples/start-server.ts`], which can also be directly invoked from the repository with `npm run demo`. Below are the important bits from that demo:
```ts
import Fastify, { FastifyInstance } from 'fastify';
import { Static, Type } from '@sinclair/typebox';
import OAS3Plugin, { OAS3PluginOptions, schemaType, oas3PluginAjv } from '../src/index.js';
```
Your imports. (Obviously, in your project, the last import will be from `"@eropple/fastify-openapi3"`.)
```ts
const fastifyOpts: FastifyServerOptions = {
logger: { level: 'error' },
ajv: {
plugins: [oas3PluginAjv],
}
}
const fastify = Fastify(fastifyOpts);
await fastify.register(OAS3Plugin, { ...pluginOpts });
```
Register the OAS3 plugin. This plugin uses the Fastify logger and can be pretty chatty on `debug`, so bear that in mind. `pluginOpts` is visible in that file for an example, but it's also commented exhaustively for your IntellSensing pleasure while you're writing it.
```ts
const PingResponse = schemaType('PingResponse', Type.Object({ pong: Type.Boolean() }));
type PingResponse = Static;
```
Your schema. `schemaType` takes a string as a name, which _must be unique for your entire project_, as well as a `@sinclair/typebox` `Type` (which you can then use as a TypeScript type by doing `Static`, it's awesome). This is now a `TaggedSchema`, which can be used anywhere a normal JSON Schema object can be used within Fastify and will handle validation as you would expect.
If you use a `TaggedSchema` within another schema, the OAS3 plugin is smart enough to extract it into its own OpenAPI `#/components/schemas/YourTypeHere` entry, so your generated clients will also only have the minimal set of model classes, etc. to worry about. Ditto having them in arrays and so on. I've tried to make this as simple to deal with as possible; if it acts in ways you don't expect, _please file an issue_.
And now let's make a route:
```ts
await fastify.register(async (fastify: FastifyInstance) => {
fastify.route<{ Reply: PingResponse }>({
url: '/ping',
method: 'GET',
schema: {
response: {
200: PingResponse,
},
},
oas: {
operationId: 'pingPingPingAndDefinitelyNotPong',
summary: "a ping to the server",
description: "This ping to the server lets you know that it has not been eaten by a grue.",
deprecated: false,
tags: ['meta'],
vendorPrefixedFields: {
"x-my-vendor-field": true,
},
},
handler: async (req, reply) => {
return { pong: true };
}
});
}, { prefix: '/api' });
```
You don't have to put yours inside a prefixed route, but I like to, so, well, there you go.
If you do a `npm run demo`, you'll get a UI that looks like the following:

And there you go.
## Autowired Security ##
This plugin includes an autowired security system that automatically handles authentication based on your OpenAPI security schemes. Define your security schemes once, and the plugin will automatically validate credentials on routes that use them.
### Basic Setup ###
```ts
await fastify.register(OAS3Plugin, {
openapiInfo: { title: 'My API', version: '1.0.0' },
autowiredSecurity: {
securitySchemes: {
ApiKey: {
type: 'apiKey',
in: 'header',
name: 'X-Api-Key',
fn: (apiKey, request) => {
return apiKey === 'secret' ? { ok: true } : { ok: false, code: 401 };
},
},
BearerAuth: {
type: 'http',
scheme: 'bearer',
fn: (token, request) => {
// Validate JWT or other bearer token
return isValidToken(token) ? { ok: true } : { ok: false, code: 401 };
},
},
},
},
});
// Use security on routes
fastify.get('/protected', {
oas: {
security: { ApiKey: [] },
},
}, async (req, reply) => {
return { data: 'secret stuff' };
});
```
### Handler Return Values ###
Security handlers return `{ ok: true }` for success, or `{ ok: false, code: 401 | 403 }` for failure:
- Return `401` (Unauthorized) when credentials are missing or invalid
- Return `403` (Forbidden) when credentials are valid but access is denied
### AND/OR Security Logic ###
OpenAPI supports combining security requirements:
```ts
// OR logic: either scheme can grant access
oas: {
security: [{ ApiKey: [] }, { BearerAuth: [] }],
}
// AND logic: both schemes must pass
oas: {
security: { ApiKey: [], BearerAuth: [] },
}
```
### Optional Credentials with `passNullIfNoneProvided` ###
By default, missing credentials return 401 immediately. Set `passNullIfNoneProvided: true` to receive `null` in your handler instead, allowing you to implement optional authentication:
```ts
securitySchemes: {
OptionalApiKey: {
type: 'apiKey',
in: 'header',
name: 'X-Api-Key',
passNullIfNoneProvided: true,
fn: (apiKey, request) => {
if (apiKey === null) {
// No key provided - allow anonymous access
return { ok: true };
}
// Key provided - validate it
return apiKey === 'secret' ? { ok: true } : { ok: false, code: 401 };
},
},
}
```
### Accessing Request Body with `requiresParsedBody` ###
Sometimes authentication decisions depend on the request body (e.g., request signing, body-based authorization). Set `requiresParsedBody: true` to receive the parsed body in your handler:
```ts
securitySchemes: {
BodyAwareAuth: {
type: 'apiKey',
in: 'header',
name: 'X-Api-Key',
requiresParsedBody: true,
fn: (apiKey, request, context) => {
// context.body contains the parsed request body
const body = context?.body as { resourceId?: string };
// Check if user has access to the requested resource
if (!userCanAccessResource(apiKey, body?.resourceId)) {
return { ok: false, code: 403 };
}
return { ok: true };
},
},
}
```
When `requiresParsedBody` is not set or is `false`, the `context` parameter will be `undefined`.
### Raw Body Access for Signature Validation ###
For webhook signature validation or HMAC verification, you need access to the raw (unparsed) request body. Use the [`fastify-raw-body`](https://github.com/Eomm/fastify-raw-body) plugin alongside `requiresParsedBody`:
```ts
import fastifyRawBody from 'fastify-raw-body';
// Register fastify-raw-body BEFORE the OAS plugin
await fastify.register(fastifyRawBody, {
global: false, // Only on routes that need it
runFirst: true, // Get raw body before any transforms
});
await fastify.register(OAS3Plugin, {
// ... other options
autowiredSecurity: {
securitySchemes: {
WebhookSignature: {
type: 'apiKey',
in: 'header',
name: 'X-Signature',
requiresParsedBody: true,
fn: (signature, request, context) => {
// request.rawBody contains the raw string/buffer
const expectedSig = crypto
.createHmac('sha256', secret)
.update(request.rawBody as string)
.digest('hex');
if (signature !== expectedSig) {
return { ok: false, code: 401 };
}
return { ok: true };
},
},
},
},
});
// Enable rawBody on specific routes
fastify.post('/webhook', {
config: { rawBody: true },
oas: { security: { WebhookSignature: [] } },
}, handler);
```
### Supported Security Schemes ###
- **API Key** (`type: 'apiKey'`): Validates keys from headers or cookies
- **HTTP Basic** (`type: 'http', scheme: 'basic'`): Validates username/password credentials
- **HTTP Bearer** (`type: 'http', scheme: 'bearer'`): Validates bearer tokens
## Contributing ##
Issues and PRs welcome! Constructive criticism on how to improve the library would be awesome, even as I use it in my own stuff and figure out where to go from there, too.
**Before you start in on a PR, however**, please do me a solid and drop an issue so we can discuss the approach. Thanks!