Square CloudSquare Cloud

What is OpenAPI (Swagger) and how to document your API

OpenAPI is an open specification for describing an HTTP API in a YAML or JSON file: routes, parameters, bodies and responses. Swagger is the standard's former name and now names tools that read that file.

Updated 6 min read

Learning objectives

After reading this article you will be able to:

  • Understand what an OpenAPI document describes and how it relates to Swagger
  • Read and write a minimal document in YAML
  • Generate the document from code and use it to validate requests and generate clients
On this page

Anyone consuming an undocumented API has to read the code, ask in chat or poke at it until something works. And documentation written by hand in a wiki goes stale with the first deploy that changes a route. OpenAPI solves both problems with a single file that people can read and programs can parse.

That file feeds the interactive documentation page, request validation, front-end types and ready-made clients in many languages. This guide shows what goes inside it, how it relates to Swagger, and how to generate and use the document day to day.

What is OpenAPI?#

OpenAPI is an open specification for describing HTTP APIs in a YAML or JSON document, independent of the language the API is written in. It is maintained by the OpenAPI Initiative, a Linux Foundation project, and published at spec.openapis.org.

For each route, an OpenAPI document answers the questions an integrator would ask:

  • Which routes exist and with which methods (GET /tasks/{id}, POST /tasks).
  • Which parameters each one takes, where (path, query, header) and of what type.
  • Which body the request carries and which responses can come back, per status code.
  • How to authenticate (API key, bearer token, OAuth).

Data shapes live in components/schemas, described with JSON Schema, and each route references them with $ref instead of repeating the definition. The document must have the openapi and info fields and, from 3.1 on, at least one of paths, components or webhooks. If you're still designing the API, start with what is a REST API.

What's the difference between OpenAPI and Swagger?#

OpenAPI is the standard; Swagger is its former name and, today, a family of tools built around it. In 2015, SmartBear donated the Swagger 2.0 specification, which became the OpenAPI Specification, maintained by the OpenAPI Initiative. Older documents still start with swagger: "2.0"; current ones start with openapi: and follow the 3.x line.

Name What it is
OpenAPI Specification The standard, maintained by the OpenAPI Initiative
Swagger 2.0 The version of the standard from before the rename
Swagger UI Turns the document into an interactive page where you can try each route in the browser
Swagger Editor A browser-based editor that validates the document as you type
Swagger Codegen Generates server stubs and client libraries from the document

In practice, when someone says "the API's Swagger docs", they almost always mean a Swagger UI page showing an OpenAPI document.

What does a minimal OpenAPI document look like?#

A task API with one route:

yaml
openapi: 3.1.0
info:
  title: Tasks API
  version: 1.0.0
paths:
  /tasks/{id}:
    get:
      summary: Get a task
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        "200":
          description: The task
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Task"
        "404":
          description: The task doesn't exist
components:
  schemas:
    Task:
      type: object
      required: [id, title]
      properties:
        id:
          type: integer
        title:
          type: string
        done:
          type: boolean

Three details trip people up at first. The openapi field is the version of the specification the document follows, while info.version is the version of your API: they're different things. Path parameters appear in braces in the route ({id}) and need required: true. And responses are keyed by the status code in quotes, because YAML would read 200 as a number.

Use the 3.x version your tools support; the list of published versions is on the specification's site.

How do you generate the document from code?#

There are two approaches. With design-first, you write the YAML before the code, agree on the contract with the people who will consume the API and implement it afterwards. With code-first, the framework reads the routes and types you already declared and generates the document itself, which keeps it from going stale.

FastAPI is the most direct code-first example: the Pydantic models that validate the request also feed the document.

python
# pip install "fastapi[standard]"
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI(title="Tasks API", version="1.0.0")


class Task(BaseModel):
    id: int
    title: str
    done: bool = False


TASKS = {1: Task(id=1, title="Buy coffee")}


@app.get("/tasks/{task_id}", response_model=Task, summary="Get a task")
def get_task(task_id: int):
    if task_id not in TASKS:
        raise HTTPException(status_code=404, detail="The task doesn't exist")
    return TASKS[task_id]

Run it with fastapi dev main.py and open /docs (Swagger UI), /redoc (ReDoc) or /openapi.json (the raw document). A request with a task_id that isn't a number comes back with a 422 before reaching your function. The comparison with Flask and Django is in which Python framework to choose.

In Node.js, support depends on the framework: Fastify has @fastify/swagger, NestJS has @nestjs/swagger and Hono has @hono/zod-openapi. In Fastify, the same JSON Schema that validates the route becomes documentation:

js
// npm install fastify @fastify/swagger @fastify/swagger-ui
// .mjs file or "type": "module" in package.json
import Fastify from "fastify";
import swagger from "@fastify/swagger";
import swaggerUi from "@fastify/swagger-ui";

const app = Fastify();

// register @fastify/swagger before the routes so it can find them
await app.register(swagger, {
  openapi: { info: { title: "Tasks API", version: "1.0.0" } },
});
await app.register(swaggerUi, { routePrefix: "/docs" });

const task = {
  type: "object",
  required: ["id", "title"],
  properties: {
    id: { type: "integer" },
    title: { type: "string" },
    done: { type: "boolean" },
  },
};

app.get(
  "/tasks/:id",
  {
    schema: {
      summary: "Get a task",
      params: {
        type: "object",
        required: ["id"],
        properties: { id: { type: "integer" } },
      },
      response: { 200: task },
    },
  },
  async (req) => ({ id: req.params.id, title: "Buy coffee", done: false }),
);

await app.listen({ host: "0.0.0.0", port: Number(process.env.PORT) || 3000 });

The page is at /docs and the document at /docs/json. Express doesn't declare a schema per route, so the usual path there is design-first: write the YAML and validate requests against it with express-openapi-validator. Choosing between these frameworks is covered in which Node.js framework to use.

What can you do with the document?#

Once it exists, the document becomes input for tools:

bash
# checks that the document follows the specification and good practices
npx @redocly/cli lint openapi.yaml

# generates TypeScript types for the front end
npx openapi-typescript openapi.yaml -o api.d.ts

# generates a full client (the generator needs Java installed)
npx @openapitools/openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o ./client
  • Interactive documentation. Swagger UI and ReDoc read the same file; integrators try routes without writing code.
  • Linting. Redocly CLI uses a recommended ruleset when there's no config file. Run it on every change, CI included, to catch responses without descriptions or broken references.
  • Validation. The document defines what a valid request is. FastAPI and Fastify already validate against the schema; in Express, express-openapi-validator does it as middleware.
  • Generated types and clients. openapi-typescript turns the document into types; OpenAPI Generator creates clients in many languages. When the API changes, you regenerate and the compiler points out what broke in the front end.

Those generated types are what brings a REST API close to GraphQL's main advantage, the typed contract. The full comparison is in REST vs GraphQL.

When is OpenAPI not the right tool?#

OpenAPI describes HTTP requests and responses. For anything outside that, other formats exist:

  • GraphQL already has the schema as its contract; an OpenAPI document there would be redundant.
  • Messaging and events (queues, MQTT, Kafka) are described with AsyncAPI, which works as a contract between whoever publishes and whoever consumes the messages.
  • Webhooks your API sends fit in OpenAPI itself, in the webhooks field (from version 3.1 on). To understand the pattern, see what is a webhook.

Two cautions apply to any API. A document written by hand and never validated slowly drifts from the truth: generate it from code or validate it in CI. And the /docs page is public by default in the frameworks that generate it; for an internal API, turn it off or protect the route, and never put real keys in the examples. Finally, don't mix up the names: OpenAPI has nothing to do with an OpenAI-compatible API.

How to do this on Square Cloud#

An API documented with OpenAPI is a web application like any other. On Square Cloud, it gets a *.squareweb.app subdomain with HTTPS on every plan, and the routes your application serves answer at that address, including the /docs page FastAPI or Fastify generates: for an internal API, turn it off before you deploy. Listen on 0.0.0.0 on the port in the PORT variable.

There's no build step: on start, the platform runs pip install -r requirements.txt for Python and npm install for Node.js when there's no node_modules. For FastAPI, an example start command, to adjust to your project, is uvicorn main:app --host 0.0.0.0 --port $PORT. The squarecloud.app file is optional: the dashboard generates it during the deploy, or you write it at the project root.

To keep the document validated, run the linter in a GitHub Actions workflow and, if it passes, ship the new version with the official GitHub Action (squarecloudofc/github-action@v2, with the required token input and command: commit <appId> --restart). See the step by step in how to host FastAPI, Flask or Django, and runtimes, plans and limits on the API hosting page.

API hosting

APIs in always-on containers, with no cold starts

API hosting

FAQs

Are OpenAPI and Swagger the same thing?

Not exactly. Swagger was the specification's name; after SmartBear donated it in 2015, it became the OpenAPI Specification, maintained by the OpenAPI Initiative. Today, Swagger is the name of tools, such as Swagger UI and Swagger Editor, that work with OpenAPI documents.

Do I have to write the OpenAPI file by hand?

Not necessarily. Frameworks such as FastAPI generate the document from your code, and Node.js has libraries for Fastify, NestJS and Hono. Writing it by hand before the code (design-first) is also a valid approach.

Is OpenAPI related to OpenAI?

No. OpenAPI is a standard for describing HTTP APIs, maintained by the OpenAPI Initiative. OpenAI is an AI company; the names only look alike.

Can I use OpenAPI with GraphQL?

It isn't the usual path. A GraphQL API already has a typed contract, the schema, which plays the role an OpenAPI document plays for a REST API.

Should the /docs page be public in production?

It depends on the API. For a public API, it helps integrators. For an internal API, turn the page off or protect the route: in FastAPI, openapi_url=None turns off the JSON and both pages at once, while docs_url=None or redoc_url=None turns off just that page.

Next articleIdempotency in APIs: what it is and how to implement itAn idempotent operation has the same effect when repeated. See which HTTP methods are idempotent and how to use the Idempotency-Key header with Redis or a database.