What is OpenAPI Spec? A Guide to REST API Documentation

What is OpenAPI Spec? A language-agnostic format for defining REST API contracts that powers documentation, testing and SDK generation.

Jump to section

Jump to section

Jump to section

The OpenAPI Specification isn't just documentation—it's the foundation that transforms how you build, maintain, and scale APIs. At Stainless, we've seen teams unlock massive productivity gains by treating their OpenAPI spec as a single source of truth that drives everything from interactive documentation and contract testing to production-ready SDKs and AI-friendly MCP servers.

This guide covers what OpenAPI is, how it maps to every stage of the API lifecycle, and practical strategies for generating SDKs and MCP servers from your spec. You'll learn the core components that make up a well-structured OpenAPI document, see real examples of specs in action, and understand how to leverage automation to keep your client libraries and AI integrations in perfect sync with your API.

What is an OpenAPI specification?

The OpenAPI Specification, often called OAS, is a standard format for defining the structure and syntax of HTTP APIs. It acts as a formal contract that details every endpoint, operation, parameter, and data model your API uses. This machine-readable contract allows tools to automatically generate documentation, client libraries, and server stubs, making it the definitive source of truth for your API's functionality.

While you might hear the term Swagger, it's important to distinguish the two. Swagger originally referred to both the specification and the tooling, but in 2015 the specification was donated to the Linux Foundation and renamed the OpenAPI Specification. Today, Swagger refers to a popular suite of tools that implement the OpenAPI standard.

Define the OpenAPI document

At its core, an OpenAPI document is a single file that organizes your API's definition into a clear structure. Even a minimal spec contains a few key sections that describe the API's metadata, server locations, and available paths.

openapi: 3.1.0
info:
  title: Simple Todos API
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /todos:
    get:
      summary: List all todos
      responses:
        '200':
          description

List the core components

An OpenAPI document is built from several key components that work together to describe the entire API surface. Understanding these building blocks is the first step to writing or reading a spec.

  • Paths: These correspond to the URL endpoints of your API, like /users or /users/{userId}.

  • Operations: Each path has one or more HTTP methods (e.g., get, post, put, delete) that define the actions you can perform.

  • Parameters: These define the inputs for an operation, such as path parameters ({userId}), query parameters (?limit=10), headers, or cookies.

  • Request Body: For operations like post or put, this describes the payload the client is expected to send.

  • Responses: This section details all possible HTTP status codes an operation can return, along with the structure of the response body for each.

  • Components: This is a reusable library of objects for your API, like data schemas, parameter definitions, and security schemes, which helps keep your spec DRY (Don't Repeat Yourself).

  • Security: This defines the authentication methods your API supports, such as API keys or OAuth 2.0.

Map OpenAPI to every stage of the API lifecycle

An OpenAPI spec is more than just documentation; it's a foundational asset that brings consistency and automation to the entire API lifecycle. By establishing a single source of truth, you can streamline processes from initial design to long-term maintenance, ensuring all teams and tools are working from the same playbook.

Drive API-first design

With an api-first approach, you create OpenAPI specs before writing a single line of implementation code. This allows frontend, backend, and QA teams to work in parallel using mock servers generated directly from the spec. This workflow mirrors the live preview experience in modern development tools, where changes to the spec instantly reflect how the final product will look and feel.

Automate documentation generation

Manually writing and updating API documentation is tedious and error-prone. An OpenAPI spec allows you to automatically generate beautiful, interactive documentation using tools like Redocly, Mintlify, or ReadMe. Furthermore, the spec can be programmatically decorated with rich code samples in multiple languages, and you can integrate SDK snippets with your API docs to give your users copy-pasteable examples for every endpoint.

Enable contract testing

The spec serves as a binding contract between your server and its clients. Automated testing tools can use it to validate that your API implementation adheres exactly to the defined specification. This practice, known as contract testing, catches breaking changes early and ensures that any changes to the API are intentional and well-documented.

Generate production SDK libraries from your spec with Stainless

Perhaps the most significant productivity gain from a well-crafted OpenAPI spec is the ability to automatically generate high-quality client libraries, or SDKs, because your API isn't finished until the SDK ships. Instead of diverting engineering resources to manually build and maintain wrappers in multiple languages, you can use a platform to transform your spec into production-ready SDKs that feel hand-crafted.

Produce idiomatic strongly typed SDKs

A generated SDK should be more than just a thin wrapper around HTTP calls. A robust generator creates idiomatic libraries with strong typing for better autocompletion and fewer runtime errors. It also handles complex boilerplate automatically, providing features like pagination helpers, request retries with exponential backoff, and seamless authentication management.

Trigger CI-driven updates

Maintaining SDKs can be a bottleneck, especially for fast-moving APIs. A modern workflow integrates SDK generation directly into your CI/CD pipeline. When you push an update to your OpenAPI spec, a process automatically regenerates the SDKs and opens pull requests in your repositories, keeping your client libraries in perfect sync with your API.

Preserve developer control

Code generation often raises concerns about losing control or the ability to add custom logic. However, an open customization loop solves this by treating the generated code as a starting point. You can add custom code like bespoke helper methods or examples directly to the SDK's repository, and subsequent code generation runs will intelligently merge your changes, preserving your work.

Expose your API to LLMs by generating an MCP server

Your OpenAPI spec can also be the source of truth for making your API accessible to AI agents. The Model Context Protocol (MCP) is an emerging open standard that defines how applications provide context and actions to Large Language Models (LLMs). By learning how to generate MCP servers from OpenAPI specs, you can enable LLMs like Claude to interact with your API using natural language.

Create tools for every endpoint

By default, each endpoint in your OpenAPI spec can be mapped to a corresponding tool that an LLM can use. For very large APIs, this can be managed with a dynamic tools mode, where the LLM can discover and learn about endpoints on demand instead of loading them all into its context window at once.

Deploy remote servers with Oauth

While local MCP servers are great for developers, real-world applications often require remote servers that can handle authentication securely. Your spec's security definitions can be used to generate a remote MCP server, often as a Cloudflare Worker or Docker image, that implements standard OAuth flows to manage user access.

Restrict or rename tools safely

You retain full control over what the LLM can access. Configuration options allow you to selectively expose or hide certain endpoints and provide custom, LLM-friendly descriptions for tools. This ensures you can safely expose your API without granting access to sensitive or destructive operations.

Apply OpenAPI in practice

Let's look at a practical example of an OpenAPI spec for a simple invoicing API. This demonstrates how the core components come together to define a real-world endpoint.

openapi: 3.1.0
info:
  title: Invoicing API
  version: 1.2.0
servers:
  - url: https://api.yourcompany.com/v1
security:
  - BearerAuth: []
paths:
  /invoices:
    get:
      summary: List Invoices
      description: Retrieves a paginated list of invoices.
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
        - name: starting_after
          in: query
          schema:
            type: string
      responses:
        '200':
          description: A list of invoices.
          content:
            application/json:
              schema:
                type: object
                properties:
                  has_more:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Invoice'
components:
  schemas:
    Invoice:
      type: object
      properties:
        id:
          type: string
          format: uuid
        amount:
          type: integer
        status:
          type: string
          enum: [draft, open, paid]
  securitySchemes:
    BearerAuth:
      type: http
      scheme

Add pagination parameters

Notice the limit and starting_after query parameters in the get /invoices operation. This is a common cursor-based pagination pattern that is more performant and robust than offset-based methods. Defining it clearly in the spec allows SDK generators to create convenient auto-paginating iterators.

Attach reusable models

The response for get /invoices doesn't define the invoice object inline. Instead, it uses $ref: '#/components/schemas/Invoice' to point to a reusable schema in the components section. This practice keeps your spec organized and ensures that the Invoice model is consistent everywhere it's used.

Secure endpoints clearly

The top-level security key applies the BearerAuth scheme to the entire API, which is defined in components/securitySchemes. This tells tools and developers that endpoints require an Authorization: Bearer <token> header, which SDKs can then abstract away with a simple client configuration.

Plan next steps with OpenAPI and Stainless

Adopting OpenAPI is a journey, but the path is well-trodden. By following a few best practices, you can create a high-quality spec that becomes a valuable, long-lasting asset for your team.

Select a spec authoring path

You have several options for creating a spec. You can write it by hand for maximum control, generate it from code comments and annotations in your existing application, or use tools that infer a spec by observing API traffic.

Validate the spec continuously

A spec is only useful if it's accurate. Integrate a linter like Spectral into your CI pipeline to enforce style guides and catch errors before they cause problems. A good generation platform will also provide diagnostics to help you improve your spec over time.

Share the spec across teams

Your spec should be easy for anyone in the organization to find and use. Store it in a version-controlled repository alongside your API code, where you can edit configs and OpenAPI specs with branches for safe testing. Enable SDK previews on pull requests so developers can see the impact of their changes, and use persistent links for easy integration with documentation providers.

Frequently asked questions about OpenAPI specs

What is OpenAPI in simple terms?

OpenAPI is a universal translator for APIs that lets different software tools speak the same language, enabling them to understand and interact with an API without needing to know its internal workings.

Which OpenAPI version should I choose?

For any new project, you should use the latest version, which is currently 3.1.0, as it offers the most features and is fully compatible with the latest JSON Schema standard.

Do I need to write specs manually?

No, you can also generate a spec from your existing code using annotation libraries or infer one from network traffic, though writing it manually often provides the cleanest result.

Can I turn my OpenAPI spec into an MCP server?

Yes, platforms like Stainless can automatically generate a Model Context Protocol (MCP) server from your OpenAPI spec, allowing AI agents to interact with your API.

How does OpenAPI help with API testing?

It enables contract testing, where you can automatically verify that your API's responses match the schemas defined in the spec, and it allows for the generation of mock servers for client-side testing.

Ready to see what your OpenAPI spec can do? Get started for free