How to make Swagger show examples of objects returned from the API?

2 min read 06-10-2024
How to make Swagger show examples of objects returned from the API?


Making Swagger Showcase API Response Examples: A Comprehensive Guide

Problem: You've meticulously documented your API using Swagger, but the response examples are missing, leaving users in the dark about the actual structure of returned data.

Solution: This article will guide you through the process of adding clear and concise examples to your Swagger documentation, making your API more user-friendly and understandable.

Scenario: You have a simple API endpoint that returns user data in a JSON format:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/users/<int:user_id>')
def get_user(user_id):
  # Simulated user data
  user = {
      "id": user_id,
      "name": "John Doe",
      "email": "[email protected]",
      "active": True,
      "role": "admin"
  }
  return jsonify(user)

if __name__ == '__main__':
  app.run(debug=True)

Original Swagger Definition:

openapi: 3.0.0
info:
  title: User API
  version: v1
paths:
  /users/{user_id}:
    get:
      summary: Get a user by ID
      parameters:
        - in: path
          name: user_id
          schema:
            type: integer
          required: true
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object

Adding Response Examples:

  1. Define the Schema: First, ensure your Swagger definition includes the appropriate schema for the returned object. In our example, we have a simple User object.

  2. Add the example property: This is where the magic happens. You can provide a concrete example of the response in your Swagger definition.

    openapi: 3.0.0
    info:
      title: User API
      version: v1
    paths:
      /users/{user_id}:
        get:
          summary: Get a user by ID
          parameters:
            - in: path
              name: user_id
              schema:
                type: integer
              required: true
          responses:
            '200':
              description: Successful response
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      id:
                        type: integer
                        example: 123
                      name:
                        type: string
                        example: John Doe
                      email:
                        type: string
                        example: [email protected]
                      active:
                        type: boolean
                        example: true
                      role:
                        type: string
                        example: admin
                  example:
                    id: 123
                    name: John Doe
                    email: [email protected]
                    active: true
                    role: admin
    

Explanation:

  • We've added the example property within the application/json content section.
  • The example property holds a concrete JSON object that represents a typical response from the API.
  • We've also provided example values for each property within the schema definition to enhance clarity.

Benefits of Adding Examples:

  • Improved User Experience: Developers can quickly understand the expected response format and data structure without needing to delve into the code.
  • Reduced Errors: Clear examples prevent misinterpretations and reduce the chances of integration errors.
  • Faster Development: Developers can easily integrate the API by using the provided examples as templates.

Beyond Basic Examples:

  • Multiple Examples: You can provide multiple examples for different scenarios, such as errors, success responses with different data, or responses with pagination information.
  • Custom Code: For complex responses, you can write custom functions or scripts to generate examples based on specific conditions or data.
  • External Sources: Some Swagger tools allow you to fetch examples from external sources, such as databases or APIs, for real-time data representation.

Conclusion:

By adding clear response examples to your Swagger documentation, you can significantly enhance the usability and developer experience of your API. This investment in clarity will pay dividends in the long run, leading to faster integration, fewer errors, and a more satisfied developer community.