Practical examples of adding response examples in Swagger documentation

If your API docs feel dry or confusing, you probably need better examples of adding response examples in Swagger documentation. Plain schemas and status codes are fine for machines, but humans want to see exactly what a `200 OK` or `422 Unprocessable Entity` looks like in real life. That’s where well-written response examples pull their weight. In this guide, we’ll walk through practical, real-world examples of adding response examples in Swagger documentation using OpenAPI 3.x. We’ll start with simple JSON payloads, then move into error formats, polymorphic responses, and versioned responses. Along the way, you’ll see how to wire up examples in YAML, annotations, and vendor-specific extensions so your docs match what your API actually returns. By the end, you’ll have a playbook of best practices and concrete examples you can lift straight into your own Swagger or OpenAPI definitions, without fighting the syntax every time you add a new endpoint.
Written by
Jamie
Published

Real-world examples of adding response examples in Swagger documentation

Let’s start where developers actually live: concrete payloads. Theory is nice, but examples of adding response examples in Swagger documentation are what turn a spec into something people trust.

Here’s a baseline OpenAPI 3.x YAML snippet for a GET /users/{id} endpoint with a simple 200 response example:

paths:
  /users/{id}:
    get:
      summary: Get a user by ID
      parameters:

        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: User found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              example:
                id: "u_12345"
                email: "jane.doe@example.com"
                fullName: "Jane Doe"
                createdAt: "2024-05-10T14:32:00Z"

This is the simplest example of a response example: a single example object at the media type level. It’s enough for most CRUD endpoints and gives consumers an immediate sense of field names, types, and formats.


Multiple success and error examples for the same endpoint

Real APIs rarely have just one happy path. You might return different payloads based on query parameters, user role, or feature flags. That’s where multiple named examples shine.

Here are examples of adding response examples in Swagger documentation that show multiple outcomes for a POST /auth/login endpoint:

paths:
  /auth/login:
    post:
      summary: Log in with email and password
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                email:
                  type: string
                  format: email
                password:
                  type: string
              required: [email, password]
      responses:
        '200':
          description: Login successful
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AuthToken'
              examples:
                basicUser:
                  summary: Basic user login
                  value:
                    accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
                    expiresIn: 3600
                    tokenType: "Bearer"
                adminUser:
                  summary: Admin login with extra claims
                  value:
                    accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
                    expiresIn: 3600
                    tokenType: "Bearer"
                    roles: ["admin", "support"]
        '401':
          description: Invalid credentials
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                wrongPassword:
                  summary: Wrong password
                  value:
                    code: "AUTH_INVALID_CREDENTIALS"
                    message: "Email or password is incorrect."
                lockedAccount:
                  summary: Account locked
                  value:
                    code: "AUTH_ACCOUNT_LOCKED"
                    message: "Too many failed attempts. Try again in 15 minutes."

These are some of the best examples to show your team how different cases are handled without forcing them to read internal code or logs.


Field-level vs media-type-level response examples

Another common question: should you put examples at the schema property level or at the content level? The answer is often “both,” but each has a different purpose.

Here’s a field-level example of a reusable schema:

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          example: "u_12345"
        email:
          type: string
          format: email
          example: "jane.doe@example.com"
        createdAt:
          type: string
          format: date-time
          example: "2024-05-10T14:32:00Z"
      required: [id, email]

These property examples show up across all endpoints that reference User. They’re great for consistency, but they don’t capture endpoint-specific variations.

Now compare that with a media-type-level example tailored for a list endpoint:

paths:
  /users:
    get:
      summary: List users
      responses:
        '200':
          description: A paginated list of users
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
                  total:
                    type: integer
                  page:
                    type: integer
                  pageSize:
                    type: integer
              example:
                data:

                  - id: "u_12345"
                    email: "jane.doe@example.com"
                    createdAt: "2024-05-10T14:32:00Z"

                  - id: "u_67890"
                    email: "john.smith@example.com"
                    createdAt: "2024-05-11T09:15:00Z"
                total: 2
                page: 1
                pageSize: 50

Both styles are valid examples of adding response examples in Swagger documentation; together, they give you reusable building blocks and endpoint-specific clarity.


Error handling: examples include structured error formats

Error responses are where many APIs fall apart. Developers need to know exactly what an error looks like to handle it gracefully. Well-structured error payloads are also increasingly recommended in security and reliability guidance from organizations like NIST and CISA.

Here are examples of adding response examples in Swagger documentation for a validation-heavy POST /orders endpoint:

paths:
  /orders:
    post:
      summary: Create a new order
      responses:
        '201':
          description: Order created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
              example:
                id: "ord_001"
                status: "pending"
                totalAmount: 129.99
        '400':
          description: Validation error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationError'
              example:
                code: "VALIDATION_ERROR"
                message: "One or more fields are invalid."
                errors:

                  - field: "items[0].quantity"
                    message: "Quantity must be at least 1."

                  - field: "shippingAddress.zip"
                    message: "ZIP code must be 5 digits."
        '422':
          description: Business rule violation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BusinessError'
              example:
                code: "OUT_OF_STOCK"
                message: "Item SKU-123 is out of stock."
                details:
                  sku: "SKU-123"
                  requested: 5
                  available: 2

These are realistic examples that match how production APIs behave in 2024–2025, especially in e‑commerce and fintech systems where validation and business rules are strict.


Language-specific examples: annotations for Java and .NET

Most teams are not hand-writing YAML all day; they’re using annotations or decorators. So let’s look at examples of adding response examples in Swagger documentation using popular tooling.

Java with Springdoc OpenAPI

@Operation(
    summary = "Get user by ID",
    responses = {
        @ApiResponse(
            responseCode = "200",
            description = "User found",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = User.class),
                examples = {
                    @ExampleObject(
                        name = "standardUser",
                        summary = "Standard user",
                        value = "{\"id\":\"u_12345\",\"email\":\"jane.doe@example.com\"}"
                    )
                }
            )
        ),
        @ApiResponse(
            responseCode = "404",
            description = "User not found",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ErrorResponse.class),
                examples = {
                    @ExampleObject(
                        name = "notFound",
                        value = "{\"code\":\"USER_NOT_FOUND\",\"message\":\"User not found\"}"
                    )
                }
            )
        )
    }
)
@GetMapping("/users/{id}")
public User getUser(@PathVariable String id) { ... }

.NET with Swashbuckle

In ASP.NET Core, you typically use ProducesResponseType and description filters or SwaggerGen configuration for examples. Here’s a simple example of wiring in a response example via an operation filter:

public class UserResponseExampleFilter : IExamplesProvider<User>
{
    public User GetExamples()
    {
        return new User
        {
            Id = "u_12345",
            Email = "jane.doe@example.com",
            CreatedAt = DateTime.UtcNow
        };
    }
}

[HttpGet("users/{id}")]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[SwaggerRequestExample(typeof(User), typeof(UserResponseExampleFilter))]
public IActionResult GetUser(string id) { ... }

Libraries change, but the pattern is consistent: define a concrete object and point Swagger tooling at it. These language-specific snippets are practical examples of adding response examples in Swagger documentation that teams can adapt immediately.


Advanced response examples: polymorphism and oneOf/anyOf

Modern APIs often return different shapes for the same status code. Think of a GET /payments/{id} endpoint that behaves differently for credit cards vs bank transfers.

Here’s an advanced example of polymorphic responses using oneOf:

components:
  schemas:
    Payment:
      oneOf:

        - $ref: '#/components/schemas/CardPayment'
        - $ref: '#/components/schemas/BankTransferPayment'
      discriminator:
        propertyName: type
        mapping:
          card: '#/components/schemas/CardPayment'
          bank_transfer: '#/components/schemas/BankTransferPayment'

    CardPayment:
      type: object
      properties:
        type:
          type: string
          example: "card"
        last4:
          type: string
          example: "4242"
        brand:
          type: string
          example: "Visa"

    BankTransferPayment:
      type: object
      properties:
        type:
          type: string
          example: "bank_transfer"
        bankName:
          type: string
          example: "First National Bank"
        routingNumber:
          type: string
          example: "021000021"

paths:
  /payments/{id}:
    get:
      summary: Get payment details
      responses:
        '200':
          description: Payment found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Payment'
              examples:
                cardPayment:
                  summary: Card payment example
                  value:
                    type: "card"
                    last4: "4242"
                    brand: "Visa"
                bankTransferPayment:
                  summary: Bank transfer example
                  value:
                    type: "bank_transfer"
                    bankName: "First National Bank"
                    routingNumber: "021000021"

These polymorphic payloads are some of the best examples when you need to show how your API handles multiple payment methods, notification channels, or authentication strategies.


Versioned and deprecation-aware response examples

By 2024–2025, versioned APIs are the norm, especially in regulated industries like healthcare and finance. That means your examples of adding response examples in Swagger documentation should reflect versioning and deprecation.

Consider a GET /v2/patients/{id} endpoint for a healthcare API (think along the lines of FHIR-style resources used by organizations like NIH):

paths:
  /v2/patients/{id}:
    get:
      summary: Get patient record (v2)
      description: |
        v2 adds `preferredLanguage` and deprecates `middleName`.
      responses:
        '200':
          description: Patient found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PatientV2'
              examples:
                current:
                  summary: Current v2 response
                  value:
                    id: "p_1001"
                    firstName: "Jane"
                    lastName: "Doe"
                    preferredLanguage: "en-US"
                legacyClient:
                  summary: Example for legacy clients
                  description: middleName kept for backward compatibility
                  value:
                    id: "p_1001"
                    firstName: "Jane"
                    middleName: "A."
                    lastName: "Doe"
                    preferredLanguage: "en-US"

Clear version-aware examples reduce surprises for integrators and help you document deprecations without breaking older clients overnight.


Best practices: keeping response examples accurate in 2024–2025

Having great examples of adding response examples in Swagger documentation is one thing; keeping them accurate as your API evolves is another. A few trends from modern API teams:

  • Contract tests that validate examples: Teams use contract-testing tools to assert that response examples in the OpenAPI spec match actual responses from staging or test environments.
  • Code generation from examples: Some organizations generate mock servers directly from examples, which forces examples to be realistic or the mocks become unusable.
  • Security-aware examples: With ongoing guidance from bodies like HHS and CDC around data privacy and security, more teams are scrubbing PII from examples and using clearly fake but realistic-looking data.

A practical approach is to treat your examples of adding response examples in Swagger documentation as test data: they should be realistic, deterministic, and reviewed during API changes, not just when the docs team has spare time.


FAQ: common questions about response examples in Swagger

How many examples of adding response examples in Swagger documentation should I provide per endpoint?

Most teams do well with at least one success and one error example per endpoint. For complex business flows, the best examples also include edge cases: rate limits, validation failures, and permission errors.

Can I reuse the same example of a response across multiple endpoints?

Yes. Define examples at the schema level in components.schemas with example or examples, then reference those schemas. This keeps your examples of adding response examples in Swagger documentation consistent across GET, POST, and PATCH operations that share the same resource.

Do examples affect how clients or servers behave?

No. Examples are documentation only; they do not change validation or runtime behavior. That said, many teams use mock servers or SDK generators that surface these examples, so inaccurate examples can still mislead consumers.

What are some best examples of error responses I should always document?

At a minimum, document 400 validation errors, 401/403 authentication and authorization failures, 404 not found, and 429 rate limiting. These are the best examples because they match the most common failure modes developers actually hit in production.

Where can I see real examples of well-documented APIs?

Look at public APIs from large providers and standards bodies. For instance, the OpenAPI Initiative maintains sample specs, and many health-related APIs referenced by organizations like NIH and CDC publish detailed schemas and examples that you can study for patterns.


If you treat your examples as first-class citizens in your OpenAPI spec, your Swagger UI stops being a static reference and becomes a living guide. The examples of adding response examples in Swagger documentation you’ve seen here are meant to be copied, tweaked, and extended until your docs tell the same story your production API does.

Explore More Using Swagger for API Definition

Discover more examples and insights in this category.

View All Using Swagger for API Definition