Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 · Documentation Tools

Swagger UI – Interactive API Documentation

Learn how Swagger UI turns an OpenAPI document into interactive docs: embedding, Docker, Try it out, authorization, CORS and configuration, with a runnable stand-in.

Swagger UI is the best-known viewer for OpenAPI documents. It reads a spec and draws a page where every operation can be expanded, read and tried out against a live server. Developers meet it as the /docs or /swagger-ui page of countless APIs. It is an open-source project from the Swagger family of tools, and works with OpenAPI 2.0, 3.0 and 3.1.

Swagger UI is a JavaScript application that needs a real server and network access, so it cannot run on this site. The configuration below is read-only. A stand-in written in JavaScript at the end of the lesson shows the core of "Try it out": turning an operation plus your inputs into a real HTTP request.

Three ways to run it

1. A static page with the swagger-ui-dist package. Install the npm package or load it from a CDN and write a short HTML file:

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Bookstore API</title>
  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
</head>
<body>
  <div id="swagger-ui"></div>
  <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
  <script>
    window.onload = () => {
      SwaggerUIBundle({
        url: "/openapi.yaml",
        dom_id: "#swagger-ui",
        deepLinking: true,
        persistAuthorization: true
      });
    };
  </script>
</body>
</html>

2. The Docker image. No code needed:

Terminal
docker run --rm -p 8081:8080 \
  -e SWAGGER_JSON=/spec/openapi.json \
  -v "$PWD:/spec" swaggerapi/swagger-ui

(SWAGGER_JSON points at a file inside the container; the URL variable points at a remote spec instead.)

3. Built into your framework. Spring (springdoc), FastAPI, NestJS, ASP.NET (Swashbuckle) and Laravel packages all serve a Swagger UI page next to the API and generate the spec from code.

What the page shows

  • Info block: title, version, description and links from info.
  • Servers selector: the servers list, so you can switch between production and staging.
  • Authorize button: appears when the spec has securitySchemes. Enter an API key or token once and Swagger UI adds it to every request.
  • Operations grouped by tag: collapsed sections with method badges and summary text.
  • Models: schemas from components/schemas, with examples and constraints.
flowchart LR
  U["You fill the form<br/>params and body"] --> B["Swagger UI builds<br/>the request"]
  B --> S["Your API server"]
  S --> R["Status, headers, body<br/>shown under the operation"]

"Try it out" sends a real request from your browser to the API.

Try it out and CORS

Because the request is sent by your browser, the API must allow it with CORS headers (Access-Control-Allow-Origin for the docs page's origin, and allowed headers such as Authorization). When "Try it out" fails with "Failed to fetch" or a network error while curl works, CORS is almost always the reason. Fix it on the API, or serve the docs from the same origin.

"Try it out" against production sends real requests. Expose it only against a sandbox or staging server, or disable it for public production docs with supportedSubmitMethods: [].

Useful configuration options

Option Effect
url or urls One spec, or a dropdown of several
docExpansion list, full or none for the initial state of operations
deepLinking Links to a specific operation via the URL hash
filter Adds a search box over tag names
persistAuthorization Keeps the entered credentials across page reloads
tagsSorter, operationsSorter Order of tags and operations (alpha, method)
defaultModelsExpandDepth -1 hides the Models section
supportedSubmitMethods Which methods get a Try it out button

Stand-in: what Try it out does

The runnable JavaScript below takes one operation from a spec and your inputs, validates required parameters, substitutes the path, adds the query string and prints the curl command that Swagger UI also shows after each call.

JS Stand-in: build a request from an operation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real UI also builds JSON bodies from your input, adds security headers from the Authorize dialog and shows the response with syntax highlighting.

Practical tips

  • Give every operation a short summary; it is the line people scan.
  • Add example values to schemas so the Try it out form starts filled in.
  • Group with tags and describe each tag at the top level.
  • Serve the spec file from the same host so the browser does not need CORS to load it.
  • Pin the swagger-ui-dist version in production rather than using a floating tag.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Try it out fails with 'Failed to fetch' but curl works. What is the most likely cause?

    Swagger UI sends requests from the browser, so cross-origin rules apply. curl is not subject to CORS.
  2. 2. Which Docker environment variable points Swagger UI at a spec file inside the container?

    SWAGGER_JSON takes a path inside the container; URL takes a remote address.
  3. 3. What does persistAuthorization do?

    It keeps the authorization the user typed so that reloading the page does not clear it.

Summary

  • Swagger UI renders interactive docs from an OpenAPI document and lets you try each operation.
  • Run it as a static page, from Docker or through your framework.
  • Try it out sends requests from the browser, so CORS must allow it; protect production with supportedSubmitMethods.
  • Configuration options control expansion, sorting, search and persistence.
  • The JavaScript request builder is a stand-in for what the UI does internally.

Next: Redoc and static documentation