# fastify version
npx fastify-cli version
```

Install the [Speakeasy CLI](/docs/speakeasy-cli/getting-started) to generate the SDK once you have generated your OpenAPI spec.

## How To Add "@fastify/swagger" to a Fastify Project

In your Fastify project folder, run the following in the terminal to install `@fastify/swagger`:

```bash
npm install --save @fastify/swagger
```

To register `@fastify/swagger` in our Fastify app, we added a new plugin. Here's the simplified plugin we added as `plugins/openapi.js`:

```javascript filename="plugins/openapi.js"
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";

export default fp(async (fastify) => {
  fastify.register(swagger);
});
```

Without any further configuration, you can generate an OpenAPI specification by running the Fastify CLI:

```bash
fastify generate-swagger app.js
```

This should print a basic OpenAPI spec in JSON format.

<Callout title="Tip" >
If you find YAML more readable than JSON, you can add `--yaml=true` to your `fastify` commands:

```bash
fastify generate-swagger --yaml=true app.js
```

The option to output YAML is [brand new](https://github.com/fastify/fastify-cli/pull/662) and, while merged, hasn't made it to a release when we wrote this tutorial.

</Callout>

## Supported OpenAPI Versions in Fastify and Speakeasy

Fastify can generate OpenAPI specifications in [OpenAPI version 2.0](https://swagger.io/specification/v2/) (formerly known as _Swagger_) or [OpenAPI version 3.0.3](https://swagger.io/specification/v3/).

Speakeasy supports OpenAPI 3.x.

We need to configure Fastify to ensure we output an OpenAPI spec that conforms to OpenAPI 3.0.3.

### How To Generate a Specification in OpenAPI Version 3.0.3 Using Fastify

In Fastify, the version of the generated OpenAPI specification is determined by the Fastify options object. To use OpenAPI 3.0.3, the options object should contain an object with the key `openapi` at its root.

Continuing our example above, we'll add an options object when we register `@fastify/swagger` in `plugins/openapi.js`:

```javascript filename="plugins/openapi.js" mark=5:7
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";

export default fp(async (fastify) => {
  fastify.register(swagger, {
    openapi: {},
  });
});
```

To verify that we now have an OpenAPI 3.0.3 spec, run:

```bash
fastify generate-swagger app.js
```

The output should start with the following JSON:

```json mark=2
{
  "openapi": "3.0.3"
  //...
}
```

## How To Add OpenAPI "info" in Fastify

Without customization, `@fastify/swagger` generates the following `info` object for our API:

```json
{
  //...
  "info": {
    "version": "8.10.1",
    "title": "@fastify/swagger"
  }
}
```

We can customize this object by updating our options object in `plugins/openapi.js`:

```javascript filename="plugins/openapi.js" mark=7:21
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";

export default fp(async (fastify) => {
  fastify.register(swagger, {
    openapi: {
      info: {
        title: "Speakeasy Bar API",
        description: "This is a sample API for Speakeasy Bar.",
        termsOfService: "http://example.com/terms/",
        contact: {
          name: "Speakeasy Bar Support",
          url: "http://www.example.com/support",
          email: "support@example.com",
        },
        license: {
          name: "Apache 2.0",
          url: "https://www.apache.org/licenses/LICENSE-2.0.html",
        },
        version: "1.0.1",
      },
    },
  });
});
```

Fastify copies this `info` object verbatim, which results in the following `info` object in our JSON:

```json
{
  "info": {
    "title": "Speakeasy Bar API",
    "description": "This is a sample API for Speakeasy Bar.",
    "termsOfService": "http://example.com/terms/",
    "contact": {
      "name": "Speakeasy Bar Support",
      "url": "http://www.example.com/support",
      "email": "support@example.com"
    },
    "license": {
      "name": "Apache 2.0",
      "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
    },
    "version": "1.0.1"
  }
  //...
}
```

Another common pattern we've seen, included here for completeness, is to reuse information from the project's `package.json` when generating OpenAPI specs. This pattern takes [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) quite literally, and someone editing the package might not realize the downstream consequences.

To pull information from `package.json` in `plugins/openapi.js`:

```javascript filename="plugins/openapi.js" mark=9:11
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";
import packageJson from "../package.json";

export default fp(async (fastify) => {
  fastify.register(swagger, {
    openapi: {
      info: {
        title: packageJson.name,
        description: packageJson.description,
        version: packageJson.version,
        //...
      },
    },
  });
});
```

## Update Fastify to Generate OpenAPI Component Schemas

Fastify handles validation and serialization for Fastify apps based on schemas defined as JSON Schema but does not enforce separating schemas into reusable components.

Let's start with a hypothetical example in a route definition, `routes/drink/index.js`:

```javascript filename="routes/drink/index.js" mark=11:16
export default async function (fastify, opts) {
  const schema = {
    params: {
      type: "object",
      properties: {
        drinkId: { type: "string" },
      },
    },
    response: {
      200: {
        type: "object",
        properties: {
          id: { type: "string" },
          name: { type: "string" },
          description: { type: "string" },
        },
      },
    },
  };

  fastify.get("/:drinkId/", { schema }, async function (request, reply) {
    const { drinkId } = request.params;
    return {
      id: drinkId,
      name: "Example Drink Name",
      description: "Example description",
    };
  });
}
```

The example above would generate the following OpenAPI schema for this route:

```json
{
  "paths": {
    "/drink/{drinkId}/": {
      "get": {
        "parameters": [
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "drinkId",
            "required": true
          }
        ],
        "responses": {
          "200": {
            "description": "Default Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "description": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```

Note how the response schema is presented inline. If we defined the schema for another route that returns a drink object similarly, our OpenAPI spec, resulting SDK, and documentation would not present a drink as a reusable component schema.

Fastify provides methods to add and reuse schemas in an application.

As a start, let's separate the response schema and use the Fastify `addSchema` method:

```javascript filename="routes/drink/index.js" mark=2:9,30
export default async function (fastify, opts) {
  fastify.addSchema({
    $id: "Drink",
    type: "object",
    properties: {
      name: { type: "string" },
      description: { type: "string" },
    },
  });

  const schema = {
    params: {
      type: "object",
      properties: {
        drinkId: { type: "string" },
      },
    },
    response: {
      200: {
        $ref: "Drink",
      },
    },
  };

  fastify.get("/:drinkId/", { schema }, async function (request, reply) {
    const { drinkId } = request.params;
    return {
      id: drinkId,
      name: "Example Drink Name",
      description: "Example description",
    };
  });
}
```

We added a field called `$id` to our drink schema, then called `fastify.addSchema()` to add this shared schema to the Fastify app. To use this shared schema, we reference it using the JSON Schema `$ref` keyword, referencing the shared schema `$id` field.

This generates the following OpenAPI schema:

```json
{
  "components": {
    "schemas": {
      "def-0": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "description": {
            "type": "string"
          }
        },
        "title": "Drink"
      }
    }
  },
  "paths": {
    "/drink/{drinkId}/": {
      "get": {
        "parameters": [
          {
            "schema": {
              "type": "string"
            },
            "in": "path",
            "name": "drinkId",
            "required": true
          }
        ],
        "responses": {
          "200": {
            "description": "Default Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/def-0"
                }
              }
            }
          }
        }
      }
    }
  }
}
```

Note how, instead of defining the response schema inline with the path schema, we now have a component schema `def-0`, which our path's response schema references as `#/components/schemas/def-0`.

This is already more useful. But if we were to generate an SDK or documentation based on this schema, the autogenerated name `def-0` would lead to documentation and methods for a schema component named `def-0`.

Our next task is to customize this name.

## Creating Useful OpenAPI "$ref" references in Fastify

By default, Fastify keeps track of all schemas added with `fastify.addSchema()` and numbers them. The default internal [function that builds these references](https://github.com/fastify/fastify-swagger/blob/ff0260811c0c319f4973665fd15517937e287040/lib/mode/dynamic.js#L17) looks like this:

```javascript filename="fastify-swagger/lib/mode/dynamic.js"
function buildLocalReference(json, baseUri, fragment, i) {
  if (!json.title && json.$id) {
    json.title = json.$id;
  }
  return `def-${i}`;
}
```

This function makes it clear where the `def-0` reference in our generated OpenAPI specification came from.

Fastify allows us to override the `buildLocalReference` function as part of our OpenAPI options object in `plugins/openapi.js`:

```javascript filename="plugins/openapi.js" mark=13:17
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";

export default fp(async (fastify) => {
  fastify.register(swagger, {
    openapi: {
      info: {
        title: "Speakeasy Bar API",
        description: "This is a sample API for Speakeasy Bar.",
        version: "1.0.1",
      },
    },
    refResolver: {
      buildLocalReference(json, baseUri, fragment, i) {
        return json.$id || `id-${i}`;
      },
    },
  });
});
```

By overriding `buildLocalReference` in the snippet above, we help Fastify to use the `$id` field as the component schema's reference. If we were to regenerate the OpenAPI spec now, we would see that `def-0` is replaced by `Drink`.

## Customizing OpenAPI "operationId" Using Fastify

Each path's `operationId` field in the OpenAPI specification is used to generate method names and documentation in SDKs.

To add `operationId` to a route, add the field to the route's schema. For example:

```javascript filename="routes/drink/index.js" mark=3
fastify.get(
  "/:drinkId/",
  { schema: { operationId: "getDrink" } },
  async function ({ params: { drinkId } }) {
    return {
      id: drinkId,
    };
  },
);
```

This would generate the following OpenAPI schema:

```json
{
  "/drink/{drinkId}/": {
    "get": {
      "operationId": "getDrink",
      "responses": {
        "200": {
          "description": "Default Response"
        }
      }
    }
  }
}
```

## Add OpenAPI Tags to Fastify Routes

At Speakeasy, whether you're building a big application or only have a handful of operations, we recommend adding tags to all your Fastify routes so you can group them by tag in generated SDK code and documentation.

### Add OpenAPI Tags to Routes in Fastify

To add OpenAPI tags to a route in Fastify, add the `tags` keyword with a list of tags to the route's schema. Here's a simplified example from `routes/drink/index.js`:

```javascript filename="routes/drink/index.js" mark=3
fastify.get(
  "/:drinkId/",
  { schema: { tags: ["drinks"] } },
  async function ({ params: { drinkId } }) {
    return {
      id: drinkId,
    };
  },
);
```

### Add Metadata to Tags

We can add a description and external documentation link to each tag by adding a list of tag objects to the Swagger options object in `plugins/openapi.js`:

```javascript filename="plugins/openapi.js" mark=8:17
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";

export default fp(async (fastify) => {
  fastify.register(swagger, {
    openapi: {
      info: {
        tags: [
          {
            name: "drinks",
            description: "Drink-related endpoints",
            externalDocs: {
              description: "Find out more",
              url: "http://swagger.io",
            },
          },
        ],
      },
    },
  });
});
```

As with the other keys in the `info` options, Fastify copies the list of tags to the generated OpenAPI spec verbatim.

## Add a List of Servers to the Fastify OpenAPI Spec

When validating an OpenAPI spec, Speakeasy expects a list of servers at the root of the spec. We'll add this to our options object in `plugins/openapi.js`:

```javascript filename="plugins/openapi.js" mark=7:12
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";

export default fp(async (fastify) => {
  fastify.register(swagger, {
    openapi: {
      servers: [
        {
          url: "http://localhost",
          description: "Development server",
        },
      ],
    },
  });
});
```

## Add Retries to Your SDK With "x-speakeasy-retries"

If you are using Speakeasy to generate your SDK, we can customize it to follow custom rules for retrying failed requests. For instance, if your server fails to return a response within a specified time, you may want your users to retry their request without clobbering your server.

Add retries to SDKs generated by Speakeasy by adding a top-level `x-speakeasy-retries` schema to your OpenAPI spec. You can also override the retry strategy per operation by adding `x-speakeasy-retries`.

### Adding Global Retries

```javascript filename="plugins/openapi.js" mark=7:17
import swagger from "@fastify/swagger";
import fp from "fastify-plugin";

export default fp(async (fastify) => {
  fastify.register(swagger, {
    openapi: {
      "x-speakeasy-retries": {
        strategy: "backoff",
        backoff: {
          initialInterval: 500,
          maxInterval: 60000,
          maxElapsedTime: 3600000,
          exponent: 1.5,
        },
        statusCodes: ["5XX"],
        retryConnectionErrors: true,
      },
    },
  });
});
```

Fastify respects OpenAPI extensions that start with `x-` and copies these to the root of the generated OpenAPI specification.

### Adding Retries per Method

If we want to add a unique retry strategy to a single route, we can add `x-speakeasy-retries` to the route's schema:

```javascript filename="routes/drink/index.js" mark=5:15
fastify.get(
  "/:drinkId/",
  {
    schema: {
      "x-speakeasy-retries": {
        strategy: "backoff",
        backoff: {
          initialInterval: 500,
          maxInterval: 60000,
          maxElapsedTime: 3600000,
          exponent: 1.5,
        },
        statusCodes: ["5XX"],
        retryConnectionErrors: true,
      },
    },
  },
  async function (request, reply) {
    const { drinkId } = request.params;
    return {
      id: drinkId,
      name: "Example Drink Name",
      description: "Example description",
    };
  },
);
```

Once again, when generating an OpenAPI spec, Fastify will copy route-specific OpenAPI extensions without any changes.

## How To Generate an SDK Based on Your OpenAPI Spec

Before generating an SDK, we need to save the Fastify-generated OpenAPI spec to a file. We'll add the following script to our `package.json` to generate `openapi.json` in the root of our project:

```json filename="package.json"
{
  "scripts": {
    "openapi": "fastify generate-swagger app.js > openapi.json"
  }
  //...
}
```

Then we run the following in the terminal:

```bash
npm run openapi
```

After following the steps above, we have an OpenAPI spec that is ready to use as the basis for a new SDK. Now we'll use Speakeasy to generate an SDK.

In the root directory of your project, run the following:

```bash
speakeasy quickstart
```

Follow the onscreen prompts to provide the necessary configuration details for your new SDK such as the name, schema location and output path. Enter `openapi.json` when prompted for the OpenAPI document location and select TypeScript when prompted for which language you would like to generate.

## Add SDK Generation to Your GitHub Actions

The Speakeasy [`sdk-generation-action`](https://github.com/speakeasy-api/sdk-generation-action) repository provides workflows that can integrate the Speakeasy CLI in your CI/CD pipeline, so your SDKs are regenerated when your OpenAPI spec changes.

You can set up Speakeasy to automatically push a new branch to your SDK repositories so that your engineers can review and merge the SDK changes.

For an overview of how to set up automation for your SDKs, see the Speakeasy documentation about [SDK Generation Action and Workflows](/docs/speakeasy-reference/workflow-file).

## Summary

In this tutorial, we've learned how to generate an OpenAPI specification for your Fastify API. We also learn how to integrate Fastify with Speakeasy to generate SDKs. The tutorial guides you through step-by-step instructions on how to do this, from adding `@fastify/swagger` to a Fastify project and generating an OpenAPI specification to improving the generated OpenAPI specification for better SDK generation.

It also covers how to use the Speakeasy OpenAPI extensions to improve generated SDKs and how to automate SDK generation as part of a CI/CD pipeline.

Following these steps, you can successfully generate OpenAPI specifications for your Fastify app and improve your API operations.