{"id":13515519,"url":"https://github.com/fastify/fastify-swagger","last_synced_at":"2025-05-12T13:21:37.839Z","repository":{"id":19450155,"uuid":"86893425","full_name":"fastify/fastify-swagger","owner":"fastify","description":"Swagger documentation generator for Fastify","archived":false,"fork":false,"pushed_at":"2025-05-01T09:37:00.000Z","size":4865,"stargazers_count":992,"open_issues_count":35,"forks_count":213,"subscribers_count":19,"default_branch":"main","last_synced_at":"2025-05-01T10:33:51.972Z","etag":null,"topics":["documentation","fastify","fastify-plugin","swagger"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/swagger","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2017-04-01T07:24:42.000Z","updated_at":"2025-05-01T09:36:56.000Z","dependencies_parsed_at":"2023-10-16T04:35:48.550Z","dependency_job_id":"e0399c41-ff89-48b5-a0d7-44b5dd377183","html_url":"https://github.com/fastify/fastify-swagger","commit_stats":{"total_commits":633,"total_committers":146,"mean_commits":4.335616438356165,"dds":0.8230647709320695,"last_synced_commit":"2b16c8a40320b451aa81b876eeef56645bc42a72"},"previous_names":[],"tags_count":140,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-swagger/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-swagger/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253745198,"owners_count":21957319,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["documentation","fastify","fastify-plugin","swagger"],"created_at":"2024-08-01T05:01:12.352Z","updated_at":"2025-05-12T13:21:37.808Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/swagger\n\n[![NPM version](https://img.shields.io/npm/v/@fastify/swagger.svg?style=flat)](https://www.npmjs.com/package/@fastify/swagger)\n[![CI](https://github.com/fastify/fastify-swagger/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-swagger/actions/workflows/ci.yml)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nA Fastify plugin for serving [Swagger (OpenAPI v2)](https://swagger.io/specification/v2/) or [OpenAPI v3](https://swagger.io/specification) schemas, which are automatically generated from your route schemas, or an existing Swagger/OpenAPI schema.\n\nIf you are looking for a plugin to generate routes from an existing OpenAPI schema, check out [fastify-openapi-glue](https://github.com/seriousme/fastify-openapi-glue).\n\nThe following plugins serve Swagger/OpenAPI front-ends based on the swagger definitions generated by this plugin:\n\n- [@fastify/swagger-ui](https://github.com/fastify/fastify-swagger-ui)\n- [@scalar/fastify-api-reference](https://github.com/scalar/scalar/tree/main/integrations/fastify)\n\nSee [the migration guide](MIGRATION.md) for migrating from `@fastify/swagger` version `\u003c=7.x` to version `\u003e=8.x`.\n\n\u003ca name=\"install\"\u003e\u003c/a\u003e\n## Install\n\n```\nnpm i @fastify/swagger\n```\n\n### Compatibility\n\n| Plugin version | Fastify version |\n| -------------- | --------------- |\n| `\u003e=9.x`        | `^5.x`          |\n| `\u003e=7.x \u003c9.x`   | `^4.x`          |\n| `^6.x`         | `^3.x`          |\n| `\u003e=3.x \u003c6.x`   | `^2.x`          |\n| `\u003e=1.x \u003c3.x`   | `^1.x`          |\n\n\nPlease note that if a Fastify version is out of support, then so are the corresponding versions of this plugin\nin the table above.\nSee [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details.\n\n\n\n\u003ca name=\"usage\"\u003e\u003c/a\u003e\n## Usage\n\nAdd it with `register`, pass it options, call the `swagger` API, and you are done! Below is an example of configuring the OpenAPI v3 specification with Fastify Swagger:\n\n```js\nconst fastify = require('fastify')()\n\nawait fastify.register(require('@fastify/swagger'), {\n  openapi: {\n    openapi: '3.0.0',\n    info: {\n      title: 'Test swagger',\n      description: 'Testing the Fastify swagger API',\n      version: '0.1.0'\n    },\n    servers: [\n      {\n        url: 'http://localhost:3000',\n        description: 'Development server'\n      }\n    ],\n    tags: [\n      { name: 'user', description: 'User related end-points' },\n      { name: 'code', description: 'Code related end-points' }\n    ],\n    components: {\n      securitySchemes: {\n        apiKey: {\n          type: 'apiKey',\n          name: 'apiKey',\n          in: 'header'\n        }\n      }\n    },\n    externalDocs: {\n      url: 'https://swagger.io',\n      description: 'Find more info here'\n    }\n  }\n})\n\nfastify.put('/some-route/:id', {\n  schema: {\n    description: 'post some data',\n    tags: ['user', 'code'],\n    summary: 'qwerty',\n    security: [{ apiKey: [] }],\n    params: {\n      type: 'object',\n      properties: {\n        id: {\n          type: 'string',\n          description: 'user id'\n        }\n      }\n    },\n    body: {\n      type: 'object',\n      properties: {\n        hello: { type: 'string' },\n        obj: {\n          type: 'object',\n          properties: {\n            some: { type: 'string' }\n          }\n        }\n      }\n    },\n    response: {\n      201: {\n        description: 'Successful response',\n        type: 'object',\n        properties: {\n          hello: { type: 'string' }\n        }\n      },\n      default: {\n        description: 'Default response',\n        type: 'object',\n        properties: {\n          foo: { type: 'string' }\n        }\n      }\n    }\n  }\n}, (req, reply) =\u003e { })\n\nawait fastify.ready()\nfastify.swagger()\n```\n\n\u003ca name=\"usage.fastify.autoload\"\u003e\u003c/a\u003e\n### With `@fastify/autoload`\n\nRegister `@fastify/swagger` before routes are loaded with `@fastify/autoload`:\n\n```js\nconst fastify = require('fastify')()\nconst fastify = fastify()\nawait fastify.register(require('@fastify/swagger'))\nfastify.register(require(\"@fastify/autoload\"), {\n  dir: path.join(__dirname, 'routes')\n})\nawait fastify.ready()\nfastify.swagger()\n```\n\n\u003ca name=\"api\"\u003e\u003c/a\u003e\n## API\n\n\u003ca name=\"register.options\"\u003e\u003c/a\u003e\n### Register options\n\n\u003ca name=\"register.options.modes\"\u003e\u003c/a\u003e\n#### Modes\n`@fastify/swagger` supports `dynamic` and `static` registration modes:\n\n\u003ca name=\"register.options.mode.dynamic\"\u003e\u003c/a\u003e\n##### Dynamic\n`dynamic` is the default mode, which auto-generates API schemas from route schemas:\n```js\n// All of the below parameters are optional but are included for demonstration purposes\n{\n  // swagger 2.0 options\n  swagger: {\n    info: {\n      title: String,\n      description: String,\n      version: String\n    },\n    externalDocs: Object,\n    host: String,\n    schemes: [ String ],\n    consumes: [ String ],\n    produces: [ String ],\n    tags: [ Object ],\n    securityDefinitions: Object\n  },\n  // openapi 3.0.3 options\n  // openapi: {\n  //   info: {\n  //     title: String,\n  //     description: String,\n  //     version: String,\n  //   },\n  //   externalDocs: Object,\n  //   servers: [ Object ],\n  //   components: Object,\n  //   security: [ Object ],\n  //   tags: [ Object ]\n  // }\n}\n```\n\nAll properties in the [Swagger (OpenAPI v2)](https://swagger.io/specification/v2/) and [OpenAPI v3](https://swagger.io/specification/) specifications can be used.\n`@fastify/swagger` generates API schemas adhering to the Swagger specification by default.\nProviding an `openapi` option generates OpenAPI compliant API schemas instead.\n\nExamples of using `@fastify/swagger` in `dynamic` mode:\n- [Using the `swagger` option](examples/dynamic-swagger.js)\n- [Using the `openapi` option](examples/dynamic-openapi.js)\n\n\u003ca name=\"register.options.mode.static\"\u003e\u003c/a\u003e\n##### Static\n `static` mode must be configured explicitly. It serves an existing Swagger or OpenAPI schema passed to `specification.path`:\n\n```js\n{\n  mode: 'static',\n  specification: {\n    path: './examples/example-static-specification.yaml',\n    postProcessor: function(swaggerObject) {\n      return swaggerObject\n    },\n    baseDir: '/path/to/external/spec/files/location',\n  },\n}\n```\n\nThe `specification.postProcessor` parameter is optional and allows modifying the Swagger object on the fly, e.g., based on the environment.\nIt accepts `swaggerObject` - a JavaScript object parsed from a `yaml` or `json` file and should return a Swagger schema object.\n\n`specification.baseDir` allows specifying the directory where all spec files that are included in the main one using `$ref` will be located.\nBy default, it is the directory of the main spec file. The value should be an absolute path **without** a trailing slash.\n\nAn example of using `@fastify/swagger` with `static` mode enabled can be found [here](examples/static-json-file.js).\n\n#### Options\n\n | Option           | Default   | Description                                                                                                                   |\n | ---------------- | --------  | ----------------------------------------------------------------------------------------------------------------------------- |\n | hiddenTag        | X-HIDDEN  | Tag to control hiding of routes.                                                                                              |\n | hideUntagged     | false     | If `true` remove routes without tags from resulting Swagger/OpenAPI schema file.                                              |\n | openapi          | {}        | [OpenAPI configuration](https://swagger.io/specification/#oasObject).                                                         |\n | stripBasePath    | true      | Strips base path from routes in docs.                                                                                         |\n | swagger          | {}        | [Swagger configuration](https://swagger.io/specification/v2/#swaggerObject).                                                  |\n | transform        | null      | Transform method for the route's schema and url. [documentation](#register.options.transform).                                |\n | transformObject  | null      | Transform method for the swagger or openapi object before it is rendered. [documentation](#register.options.transformObject). |\n | refResolver      | {}        | Option to manage the `$ref`s of the application's schemas. Read the [`$ref` documentation](#register.options.refResolver)    |\n | exposeHeadRoutes | false     | Include HEAD routes in the definitions                                                                                        |\n | decorator        | 'swagger' | Overrides the Fastify decorator. [documentation](#register.options.decorator).                                                |\n\n\u003ca name=\"register.options.transform\"\u003e\u003c/a\u003e\n#### Transform\n\nPass a synchronous `transform` function to modify the route's URL and schema.\n`openapiObject` and `swaggerObject` are also available.\n\nSome possible uses of this are:\n- Adding the `hide` flag to the schema based on URL and schema logic\n- Altering the route URL to suit the API spec\n- Transforming different schemas (e.g., [Joi](https://github.com/hapijs/joi)) to standard JSON schemas\n- Hiding routes based on version constraints\n\nThis option is available in `dynamic` mode only.\n\nExamples of all the possible uses mentioned:\n\n```js\nconst convert = require('joi-to-json')\n\nawait fastify.register(require('@fastify/swagger'), {\n  swagger: { ... },\n  transform: ({ schema, url, route, swaggerObject }) =\u003e {\n    const {\n      params,\n      body,\n      querystring,\n      headers,\n      response,\n      ...transformedSchema\n    } = schema\n    let transformedUrl = url\n\n    // Transform the schema as you wish with your own custom logic.\n    // In this example convert is from 'joi-to-json' lib and converts a Joi based schema to json schema\n    if (params) transformedSchema.params = convert(params)\n    if (body) transformedSchema.body = convert(body)\n    if (querystring) transformedSchema.querystring = convert(querystring)\n    if (headers) transformedSchema.headers = convert(headers)\n    if (response) transformedSchema.response = convert(response)\n\n    // can add the hide tag if needed\n    if (url.startsWith('/internal')) transformedSchema.hide = true\n\n    // can transform the url\n    if (url.startsWith('/latest_version/endpoint')) transformedUrl = url.replace('latest_version', 'v3')\n\n    // can add the hide tag for routes that do not match the swaggerObject version\n    if (route?.constraints?.version !== swaggerObject.swagger) transformedSchema.hide = true\n\n    return { schema: transformedSchema, url: transformedUrl }\n  }\n})\n```\n\nThe transform function can also be attached to a specific endpoint:\n\n```js\nfastify.get(\"/\", {\n  schema: { ... },\n  config: {\n    swaggerTransform: ({ schema, url, route, swaggerObject }) =\u003e { ... }\n  }\n})\n```\n\nIf both global and local transform functions are available for an endpoint, the endpoint-specific transform function is used.\n\nThe local transform function is useful for adding information to a specific endpoint, applying different transformations, or ignoring the global transform function.\n\nThe global transform function can be disabled by passing `false` instead of a function.\n\n\u003ca name=\"register.options.transformObject\"\u003e\u003c/a\u003e\n#### Transform Object\n\nBy passing a synchronous `transformObject` function you can modify the resulting `swaggerObject` or `openapiObject` before it is rendered.\n\n```js\nawait fastify.register(require('@fastify/swagger'), {\n  swagger: { ... },\n  transformObject ({ swaggerObject }) =\u003e {\n    swaggerObject.info.title = 'Transformed';\n    return swaggerObject;\n  }\n})\n```\n\n\u003ca name=\"register.options.refResolver\"\u003e\u003c/a\u003e\n#### Managing your `$ref`s\n\nIn `dynamic` mode, this plugin resolves all `$ref`s in the application's schemas, creating a new in-line schema that references itself.\nThis ensures the generated documentation is valid, preventing Swagger UI from failing to fetch schemas from the server or network.\n\nBy default, this option resolves all `$ref`s, renaming them to `def-${counter}`, while view models keep the original `$id` naming using the [`title` parameter](https://swagger.io/docs/specification/2-0/basic-structure/#metadata).\n\nThis logic can be customized by passing a `refResolver` option to the plugin:\n\n```js\nawait fastify.register(require('@fastify/swagger'), {\n  swagger: { ... },\n  ...\n  refResolver: {\n    buildLocalReference (json, baseUri, fragment, i) {\n      return json.$id || `my-fragment-${i}`\n    }\n  }\n}\n```\n\nFor details on `buildLocalReference` arguments, see the [documentation](https://github.com/Eomm/json-schema-resolver#usage-resolve-one-schema-against-external-schemas).\n\n\u003ca name=\"register.options.decorator\"\u003e\u003c/a\u003e\n#### Decorator\n\nThe default decorate function (`fastify.swagger()`) can be overridden by passing a string to the `decorator` option. This allows creating multiple documents by registering `@fastify/swagger` multiple times with different `transform` functions:\n\n```js\n// Create an internal Swagger doc\nawait fastify.register(require('@fastify/swagger'), {\n  swagger: { ... },\n  transform: ({ schema, url, route, swaggerObject }) =\u003e {\n    const {\n      params,\n      body,\n      querystring,\n      headers,\n      response,\n      ...transformedSchema\n    } = schema\n    let transformedUrl = URL\n\n    // Hide external URLs\n    if (url.startsWith('/external')) transformedSchema.hide = true\n\n    return { schema: transformedSchema, url: transformedUrl }\n  },\n  decorator: 'internalSwagger'\n})\n\n// Create an external Swagger doc\nawait fastify.register(require('@fastify/swagger'), {\n  swagger: { ... },\n  transform: ({ schema, url, route, swaggerObject }) =\u003e {\n    const {\n      params,\n      body,\n      querystring,\n      headers,\n      response,\n      ...transformedSchema\n    } = schema\n    let transformedUrl = URL\n\n    // Hide internal URLs\n    if (url.startsWith('/internal')) transformedSchema.hide = true\n\n    return { schema: transformedSchema, url: transformedUrl }\n  },\n  decorator: 'externalSwagger'\n})\n```\n\nThen call those decorators individually to retrieve them:\n```\nfastify.internalSwagger()\nfastify.externalSwagger()\n```\n\n\u003ca name=\"route.options\"\u003e\u003c/a\u003e\n### Route options\n\n`HEAD` routes can be included in the definitions by adding `exposeHeadRoute` in the route config:\n\n```js\n  fastify.get('/with-head', {\n    schema: {\n      operationId: 'with-head',\n      response: {\n        200: {\n          description: 'Expected Response',\n          type: 'object',\n          properties: {\n            foo: { type: 'string' }\n          }\n        }\n      }\n    },\n    config: {\n      swagger: {\n        exposeHeadRoute: true,\n      }\n    }\n  }, () =\u003e {})\n```\n\n\u003ca name=\"route.response.options\"\u003e\u003c/a\u003e\n#### Response Options\n\n\u003ca name=\"route.response.description\"\u003e\u003c/a\u003e\n##### Response description and response body description\n`description` is required by the Swagger specification. If not provided, the plugin defaults to `'Default Response'`.\nIf a `description` is supplied, it will be used for both the response and response body schema:\n\n```js\nfastify.get('/description', {\n  schema: {\n    response: {\n      200: {\n        description: 'response and schema description',\n        type: 'string'\n      }\n    }\n  }\n}, () =\u003e {})\n```\n\nGenerates this in a Swagger (OpenAPI v2) schema's `paths`:\n\n```json\n{\n  \"/description\": {\n    \"get\": {\n      \"responses\": {\n        \"200\": {\n          \"description\": \"response and schema description\",\n          \"schema\": {\n            \"description\": \"response and schema description\",\n            \"type\": \"string\"\n          }\n        }\n      }\n    }\n  }\n}\n```\n\nAnd this in an OpenAPI v3 schema's `paths`:\n\n```json\n{\n  \"/description\": {\n    \"get\": {\n      \"responses\": {\n        \"200\": {\n          \"description\": \"response and schema description\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"description\": \"response and schema description\",\n                \"type\": \"string\"\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n```\n\nTo provide different descriptions for the response and response body, use the `x-response-description` field alongside `description`:\n\n```js\nfastify.get('/responseDescription', {\n  schema: {\n    response: {\n      200: {\n        'x-response-description': 'response description',\n        description: 'schema description',\n        type: 'string'\n      }\n    }\n  }\n}, () =\u003e {})\n```\n\nIf a `$ref` is provided in the response schema without a description, the reference's description will be used as a fallback. Currently, `$ref` is resolved by matching with `$id` only, not through complex paths.\n\n\u003ca name=\"route.response.2xx\"\u003e\u003c/a\u003e\n##### Status code 2xx\nFastify supports `2xx` and `3xx` status codes, but Swagger (OpenAPI v2) does not.\n`@fastify/swagger` transforms `2xx` into `200`, omitting it if `200` is already declared.\nOpenAPI v3 supports [`2xx` syntax](https://swagger.io/specification/#http-codes) so is unaffected.\n\nExample:\n\n```js\n{\n  response: {\n    '2xx': {\n      description: '2xx',\n      type: 'object'\n    }\n  }\n}\n\n// will become\n{\n  response: {\n    200: {\n      schema: {\n        description: '2xx',\n        type: 'object'\n      }\n    }\n  }\n}\n```\n\u003ca name=\"route.response.headers\"\u003e\u003c/a\u003e\n##### Response headers\nResponse headers can be decorated with the following example.\nSpecify the `type` property when decorating response headers to prevent schema modification by Fastify.\n\n```js\n{\n  response: {\n    200: {\n      type: 'object',\n      headers: {\n        'X-Foo': {\n          type: 'string'\n        }\n      }\n    }\n  }\n}\n```\n\n\u003ca name=\"route.response.empty_body\"\u003e\u003c/a\u003e\n##### Different content types responses\n\u003e 🛈 Note: Supported [only by OpenAPI v3](https://swagger.io/docs/specification/describing-responses/), not Swagger (OpenAPI v2).\n\nDifferent content types are supported by `@fastify/swagger` and `@fastify`.\nUse `content` for the response to prevent Fastify from failing to compile the schema:\n\n```js\n{\n  response: {\n    200: {\n      description: 'Description and all status-code based properties are working',\n      content: {\n        'application/json': {\n          schema: {\n            name: { type: 'string' },\n            image: { type: 'string' },\n            address: { type: 'string' }\n          }\n        },\n        'application/vnd.v1+json': {\n          schema: {\n            fullName: { type: 'string' },\n            phone: { type: 'string' }\n          }\n        }\n      }\n    }\n  }\n}\n```\n##### Empty Body Responses\nEmpty body responses are supported by `@fastify/swagger`.\nSpecify `type: 'null'` for the response to prevent Fastify from failing to compile the schema:\n\n```js\n{\n  response: {\n    204: {\n      type: 'null',\n      description: 'No Content'\n    },\n    503: {\n      type: 'null',\n      description: 'Service Unavailable'\n    }\n  }\n}\n```\n\n\u003ca name=\"route.openapi\"\u003e\u003c/a\u003e\n#### OpenAPI Parameter Options\n\n\u003e 🛈 Note: OpenAPI's terminology differs from Fastify's. OpenAPI uses \"parameter\" to refer to parts of a request that in [Fastify's validation documentation](https://fastify.dev/docs/latest/Reference/Validation-and-Serialization/) are called \"querystring\", \"params\", and \"headers\".\n\nOpenAPI extends the [JSON schema specification](https://json-schema.org/specification.html) with options like `collectionFormat` for encoding array parameters.\n\nThese encoding options only affect how Swagger UI presents documentation and generates `curl` commands.\nDepending on the schema options, you may need to change Fastify's default query string parser to produce a JavaScript object conforming to the schema.\nThe default parser conforms to `collectionFormat: \"multi\"`.\nFor `collectionFormat: \"csv\"`, replace the default parser with one that parses CSV values into arrays. This applies to other request parts that OpenAPI calls \"parameters\" and are not encoded as JSON.\n\nDifferent serialization `style` and `explode` can also be applied as specified [here](https://swagger.io/docs/specification/serialization/#query).\n\n`@fastify/swagger` supports these options as shown in this example:\n\n```js\n// Need to add a collectionFormat keyword to ajv in fastify instance\nconst fastify = Fastify({\n  ajv: {\n    customOptions: {\n      keywords: ['collectionFormat']\n    }\n  }\n})\n\nfastify.route({\n  method: 'GET',\n  url: '/',\n  schema: {\n    querystring: {\n      type: 'object',\n      required: ['fields'],\n      additionalProperties: false,\n      properties: {\n        fields: {\n          type: 'array',\n          items: {\n            type: 'string'\n          },\n          minItems: 1,\n          //\n          // Note that this is an OpenAPI version 2 configuration option. The\n          // options changed in version 3.\n          //\n          // Put `collectionFormat` on the same property which you are defining\n          // as an array of values. (i.e. `collectionFormat` should be a sibling\n          // of the `type: \"array\"` specification.)\n          collectionFormat: 'multi'\n        }\n      },\n     // OpenAPI 3 serialization options\n     explode: false,\n     style: \"deepObject\"\n    }\n  },\n  handler (request, reply) {\n    reply.send(request.query.fields)\n  }\n})\n```\n\nThere is a complete runnable example [here](examples/collection-format.js).\n\n\u003ca name=\"route.complex-serialization\"\u003e\u003c/a\u003e\n#### Complex serialization in query and cookie, eg. JSON\n\n\u003e 🛈 Note: Supported [only by OpenAPI v3](https://swagger.io/docs/specification/describing-parameters/#schema-vs-content), not Swagger (OpenAPI v2).\n\n```\nhttp://localhost/?filter={\"foo\":\"baz\",\"bar\":\"qux\"}\n```\n\n\u003e 🛈 Note: Change Fastify's default query string parser to produce a JavaScript object conforming to the schema. See [example](examples/json-in-querystring.js).\n\n```js\nfastify.route({\n  method: 'GET',\n  url: '/',\n  schema: {\n    querystring: {\n      type: 'object',\n      required: ['filter'],\n      additionalProperties: false,\n      properties: {\n        filter: {\n          type: 'object',\n          required: ['foo'],\n          properties: {\n            foo: { type: 'string' },\n            bar: { type: 'string' }\n          },\n          'x-consume': 'application/json'\n        }\n      }\n    }\n  },\n  handler (request, reply) {\n    reply.send(request.query.filter)\n  }\n})\n```\n\nGenerates this in the OpenAPI v3 schema's `paths`:\n\n```json\n{\n  \"/\": {\n    \"get\": {\n      \"parameters\": [\n        {\n          \"in\": \"query\",\n          \"name\": \"filter\",\n          \"required\": true,\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"foo\"\n                ],\n                \"properties\": {\n                  \"foo\": {\n                    \"type\": \"string\"\n                  },\n                  \"bar\": {\n                    \"type\": \"string\"\n                  }\n                }\n              }\n            }\n          }\n        }\n      ]\n    }\n  }\n}\n```\n\n##### Route parameters\n\nRoute parameters in Fastify are called params.\nThese are values included in the URL of the requests, for example:\n\n```js\nfastify.route({\n  method: 'GET',\n  url: '/:id',\n  schema: {\n    params: {\n      type: 'object',\n      properties: {\n        id: {\n          type: 'string',\n          description: 'user id'\n        }\n      }\n    }\n  },\n  handler (request, reply) {\n    reply.send(request.params.id)\n  }\n})\n```\n\nGenerates this in the Swagger (OpenAPI v2) schema's `paths`:\n\n```json\n{\n  \"/{id}\": {\n    \"get\": {\n      \"parameters\": [\n        {\n          \"type\": \"string\",\n          \"description\": \"user id\",\n          \"required\": true,\n          \"in\": \"path\",\n          \"name\": \"id\"\n        }\n      ],\n      \"responses\": {\n        \"200\": {\n          \"description\": \"Default Response\"\n        }\n      }\n    }\n  }\n}\n```\n\nGenerates this in the OpenAPI v3 schema's `paths`:\n\n```json\n{\n  \"/{id}\": {\n    \"get\": {\n      \"parameters\": [\n        {\n          \"schema\": {\n            \"type\": \"string\"\n          },\n          \"in\": \"path\",\n          \"name\": \"id\",\n          \"required\": true,\n          \"description\": \"user id\"\n        }\n      ],\n      \"responses\": {\n        \"200\": {\n          \"description\": \"Default Response\"\n        }\n      }\n    }\n  }\n}\n```\n\nWhen `params` is not present in the schema, or a schema is not provided, parameters are automatically generated:\n\n```js\nfastify.route({\n  method: 'POST',\n  url: '/:id',\n  handler (request, reply) {\n    reply.send(request.params.id)\n  }\n})\n```\n\nGenerates this in the Swagger (OpenAPI v2) schema's `paths`:\n\n```json\n{\n  \"/{id}\": {\n    \"get\": {\n      \"parameters\": [\n        {\n          \"type\": \"string\",\n          \"required\": true,\n          \"in\": \"path\",\n          \"name\": \"id\"\n        }\n      ],\n      \"responses\": {\n        \"200\": {\n          \"description\": \"Default Response\"\n        }\n      }\n    }\n  }\n}\n```\n\nGenerates this in the OpenAPI v3 schema's `paths`:\n\n```json\n{\n  \"/{id}\": {\n    \"get\": {\n      \"parameters\": [\n        {\n          \"schema\": {\n            \"type\": \"string\"\n          },\n          \"in\": \"path\",\n          \"name\": \"id\",\n          \"required\": true\n        }\n      ],\n      \"responses\": {\n        \"200\": {\n          \"description\": \"Default Response\"\n        }\n      }\n    }\n  }\n}\n```\n\n\u003ca name=\"route.links\"\u003e\u003c/a\u003e\n#### Links\n\n\u003e 🛈 Note: Supported [only by OpenAPI v3](https://swagger.io/docs/specification/links), not Swagger (OpenAPI v2).\n\nAdd OpenAPI v3 Links by adding a `links` property to the top-level options of a route. See:\n\n```js\nfastify.get('/user/:id', {\n  schema: {\n    params: {\n      type: 'object',\n      properties: {\n        id: {\n          type: 'string',\n          description: 'the user identifier, as userId'\n        }\n      },\n      required: ['id']\n    },\n    response: {\n      200: {\n        type: 'object',\n        properties: {\n          uuid: {\n            type: 'string',\n            format: 'uuid'\n          }\n        }\n      }\n    }\n  },\n  links: {\n    // The status code must match the one in the response\n    200: {\n      address: {\n        // See the OpenAPI documentation\n        operationId: 'getUserAddress',\n        parameters: {\n          id: '$request.path.id'\n        }\n      }\n    }\n  }\n}, () =\u003e {})\n\nfastify.get('/user/:id/address', {\n  schema: {\n    operationId: 'getUserAddress',\n    params: {\n      type: 'object',\n      properties: {\n        id: {\n          type: 'string',\n          description: 'the user identifier, as userId'\n        }\n      },\n      required: ['id']\n    },\n    response: {\n      200: {\n        type: 'string'\n      }\n    }\n  }\n}, () =\u003e {})\n```\n\n\u003ca name=\"route.hide\"\u003e\u003c/a\u003e\n#### Hide a route\nThere are two ways to hide a route from the Swagger UI:\n- Pass `{ hide: true }` to the schema object inside the route declaration.\n- Use the tag declared in `hiddenTag` options property inside the route declaration. Default is `X-HIDDEN`.\n\n\u003ca name=\"function.options\"\u003e\u003c/a\u003e\n### Swagger function options\n\nRegistering `@fastify/swagger` decorates the fastify instance with `fastify.swagger()`, which returns a JSON object representing the API.\nIf `{ yaml: true }` is passed to `fastify.swagger()` it returns a YAML string.\n\n\u003ca name=\"integration\"\u003e\u003c/a\u003e\n### Integration\n\nThis plugin can be integrated with `@fastify/helmet` with minimal effort:\n```js\n.register(helmet, instance =\u003e {\n  return {\n    contentSecurityPolicy: {\n      directives: {\n        ...helmet.contentSecurityPolicy.getDefaultDirectives(),\n        \"form-action\": [\"'self'\"],\n        \"img-src\": [\"'self'\", \"data:\", \"validator.swagger.io\"],\n        \"script-src\": [\"'self'\"].concat(instance.swaggerCSP.script),\n        \"style-src\": [\"'self'\", \"https:\"].concat(\n          instance.swaggerCSP.style\n        ),\n      }\n    }\n  }\n})\n```\n\n\u003ca name=\"schema.examplesField\"\u003e\u003c/a\u003e\n### Add examples to the schema\n\n[OpenAPI](https://swagger.io/specification/#example-object) and [JSON Schema](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.9.5) have different examples field formats.\n\nArray with examples from JSON Schema converted to OpenAPI `example` or `examples` field automatically with generated names (example1, example2...):\n\n```js\nfastify.route({\n  method: 'POST',\n  url: '/',\n  schema: {\n    querystring: {\n      type: 'object',\n      required: ['filter'],\n      properties: {\n        filter: {\n          type: 'object',\n          required: ['foo'],\n          properties: {\n            foo: { type: 'string' },\n            bar: { type: 'string' }\n          },\n          examples: [\n            { foo: 'bar', bar: 'baz' },\n            { foo: 'foo', bar: 'bar' }\n          ]\n        }\n      },\n      examples: [\n        { filter: { foo: 'bar', bar: 'baz' } }\n      ]\n    }\n  },\n  handler (request, reply) {\n    reply.send(request.query.filter)\n  }\n})\n```\n\nGenerates this in the OpenAPI v3 schema's `paths`:\n\n```json\n\"/\": {\n  \"post\": {\n    \"requestBody\": {\n      \"content\": {\n        \"application/json\": {\n          \"schema\": {\n            \"type\": \"object\",\n            \"required\": [\"filter\"],\n            \"properties\": {\n              \"filter\": {\n                \"type\": \"object\",\n                \"required\": [\"foo\"],\n                \"properties\": {\n                  \"foo\": { \"type\": \"string\" },\n                  \"bar\": { \"type\": \"string\" }\n                },\n                \"example\": { \"foo\": \"bar\", \"bar\": \"baz\" }\n              }\n            }\n          },\n          \"examples\": {\n            \"example1\": {\n              \"value\": { \"filter\": { \"foo\": \"bar\", \"bar\": \"baz\" } }\n            },\n            \"example2\": {\n              \"value\": { \"filter\": { \"foo\": \"foo\", \"bar\": \"bar\" } }\n            }\n          }\n        }\n      },\n      \"required\": true\n    },\n    \"responses\": { \"200\": { \"description\": \"Default Response\" } }\n  }\n}\n```\n\nUse the `x-examples` field to set names or add descriptions to schema examples in [OpenAPI format](https://swagger.io/specification/#example-object):\n\n```js\n// Need to add a new allowed keyword to ajv in fastify instance\nconst fastify = Fastify({\n  ajv: {\n    plugins: [\n      function (ajv) {\n        ajv.addKeyword({ keyword: 'x-examples' })\n      }\n    ]\n  }\n})\n\nfastify.route({\n  method: 'POST',\n  url: '/feed-animals',\n  schema: {\n    body: {\n      type: 'object',\n      required: ['animals'],\n      properties: {\n        animals: {\n          type: 'array',\n          items: {\n            type: 'string'\n          },\n          minItems: 1,\n        }\n      },\n      \"x-examples\": {\n        Cats: {\n          summary: \"Feed cats\",\n          description:\n            \"A longer **description** of the options with cats\",\n          value: {\n            animals: [\"Tom\", \"Garfield\", \"Felix\"]\n          }\n        },\n        Dogs: {\n          summary: \"Feed dogs\",\n          value: {\n            animals: [\"Spike\", \"Odie\", \"Snoopy\"]\n          }\n        }\n      }\n    }\n  },\n  handler (request, reply) {\n    reply.send(request.body.animals)\n  }\n})\n```\n\n\u003ca name=\"usage\"\u003e\u003c/a\u003e\n## `$id` and `$ref` usage\n\n### How to work with $refs\n\nThe `/docs/json` endpoint in dynamic mode produces a single `swagger.json` file, resolving all of the references.\n\n## Acknowledgments\n\nThis project is kindly sponsored by:\n- [nearForm](https://nearform.com)\n- [LetzDoIt](https://www.letzdoitapp.com/)\n\n\u003ca name=\"license\"\u003e\u003c/a\u003e\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["JavaScript","\u003ch2 align=\"center\"\u003eAwesome Fastify\u003c/h2\u003e"],"sub_categories":["\u003ch2 align=\"center\"\u003eEcosystem\u003c/h2\u003e"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-swagger","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-swagger","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-swagger/lists"}