<a id="how-to-openapi"></a>

# Add OpenAPI integration

OpenAPI specifications provide a standardized way to document REST APIs.
This guide demonstrates how to add a minimal OpenAPI integration to your project using [Swagger UI](https://swagger.io/tools/swagger-ui/), including a basic specification and an opt-in tag toggle based on a build-time environment variable to keep the documentation clean by default.

## Locate the specification

The stub OpenAPI document can be found under `docs/how-to/assets/openapi.yaml`.
You can use it as a starting point for your API description:

```yaml
openapi: 3.0.3
info:
  title: Hello API
  version: 1.0.0
paths:
  /hello:
    get:
      summary: Say hello
      parameters:
        - in: query
          name: name
          schema:
            type: string
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: "Hello, world!"
```

## Enable the viewer

The OpenAPI interactive viewer is disabled by default.
Exporting the `OPENAPI` environment variable when building in your terminal
makes Sphinx copy the specification to the output directory
and add an `openapi` tag that we can use in the documentation source:

```none
export OPENAPI=1
```

Then rebuild the docs to pick up the specification:

```none
make clean html
```

#### TIP
Unset the variable to go back to the default build:

```none
unset OPENAPI
```

To enable it for a single command, prefix it like this:

```none
OPENAPI=1 make clean html
```

## Confirm the viewer works

Serve the documentation locally:

```none
make run
```

Navigate to `/how-to/openapi/`.
When the feature flag is enabled,
the page renders the Swagger UI for the shipped specification right here.
The snippet that does this should be included in your documentation source
with the `.. raw:: html` directive:

```html

   <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
   <div id="openapi-hello-swagger"></div>
   <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js" charset="UTF-8"
       crossorigin="anonymous"></script>
   <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-standalone-preset.js" charset="UTF-8"
       crossorigin="anonymous"></script>
   <script>
       window.addEventListener('load', function () {
           const specUrl = new URL('/openapi.yaml', window.location.href).toString();
           SwaggerUIBundle({
               url: specUrl,
               dom_id: '#openapi-hello-swagger',
               presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
               plugins: [],
               deepLinking: true,
               defaultModelsExpandDepth: -1,
               supportedSubmitMethods: []
           });
       });
   </script>
```

#### WARNING
The interactive viewer is hidden now because `OPENAPI` was not set
when this documentation was built.
Export `OPENAPI=1` when building the documentation to see it here.

## Building on RTD

To enable the OpenAPI viewer on [Read the Docs](https://readthedocs.org/) tentatively,
define the `OPENAPI` environment variable in your project’s
[admin settings](https://docs.readthedocs.com/platform/stable/guides/environment-variables.html).

If you’re certain that you want the OpenAPI viewer enabled for all builds,
drop all conditional statements from `conf.py` and the reST files.
In `conf.py`, replace the following lines:

```none
html_extra_path = []

# ...
if os.getenv("OPENAPI", ""):
    tags.add("openapi")
    html_extra_path.append("how-to/assets/openapi.yaml")
```

With this:

```none
html_extra_path = ["how-to/assets/openapi.yaml"]
```

Next, remove any tag-based logic from the reST files:

```none
.. only:: openapi
```

## Troubleshooting

* The `make html` command fails with unknown tag:
  Make sure you exported the environment variable
  in the same shell session that runs `make`.
* The Swagger UI appears but cannot load the specification:
  Make sure that `openapi.yaml` exists in the *root* of your build output
  or adjust the import paths according to your build structure.
  Also, overriding the `html_extra_path` setting in `conf.py`
  may interfere with this configuration
  because it is used to copy the specification to the output directory.
