Swagger Open Source Documentation

repository·main·Indexed 23 days ago

https://github.com/swagger-api/swagger.io-docs

Official documentation for the Swagger tool suite and the OpenAPI Specification. Includes comprehensive guides for Swagger Codegen v2, covering the generation of API client libraries, server stubs, and static HTML documentation from OpenAPI specifications (versions 1.0 through 2.0). Provides instructions for local development using Astro, CLI usage, Docker integration, and selective code generation.

Tokens
92K
Snippets
308
Records
386
Agent score
81%

What's inside swagger.io-docs

  1. Overview of Swagger Codegen v3

    main

    Swagger Codegen is an open-source tool that automatically generates API client libraries (SDKs), server stubs, and documentation from an OpenAPI Description.

    Key Versioning Information:

    • v3.X (io.swagger.codegen.v3): Supports OpenAPI 3.0.X. This is the recommended version for modern specifications.
    • v2.X (io.swagger): Supports OpenAPI 1.0, 1.1, 1.2, and 2.0.

    Security Warning: If the OpenAPI Description or Swagger file is obtained from an untrusted source, review the artifact before use to prevent potential code injection.

  2. Overview of Swagger Codegen v2

    main

    Swagger Codegen is a tool used to automatically generate API client libraries (SDKs), server stubs, and documentation from an OpenAPI Specification.

    Key Versioning Notes:

    • This documentation refers to version 2.X (group ID io.swagger).
    • Version 3.X (group ID io.swagger.codegen.v3) is independently maintained and is the only version that supports OpenAPI 3.0.X.
    • If you are using an OpenAPI 3.0.X spec, you must use the 3.X version of the tool.
  3. What is Swagger and the OpenAPI Specification

    main

    Swagger is a toolset that uses the OpenAPI Specification (OAS) to describe the structure of your APIs in a machine-readable YAML or JSON format. This specification acts as a resource listing that defines your API's operations, parameters, return types, authorization requirements, and metadata (such as contact info and licenses).

    By providing a Swagger spec, you can:

    • Automatically build interactive API documentation.
    • Generate client libraries in multiple languages.
    • Enable automated testing.
    • Integrate with various API-related tools.
  4. What is a Swagger UI plugin?

    main

    A plugin is a function that returns an object used to augment or modify Swagger UI's functionality. The returned object can contain state plugins (actions, reducers, selectors, etc.), components, component wrappers, root injections, and lifecycle methods.

    Important: Dependency Management There is no built-in dependency management. If your plugin relies on another, you must ensure the dependent plugin is loaded after the required plugin.

    Important: Semantic Versioning Swagger UI's internal APIs are not part of the public contract and may change without a major version change. If your plugin wraps or extends internal core APIs, pin your dependency to a specific minor version using a tilde (e.g., "swagger-ui": "~3.11.0") to ensure stability across patch updates.

    {
      statePlugins: {
        [stateKey]: {
          actions,
          reducers,
          selectors,
          wrapActions,
          wrapSelectors
        }
      },
      components: {},
      wrapComponents: {},
      rootInjects: {},
      afterLoad: (system) => {},
      fn: {},
    }
  5. Combine multiple authentication types using AND/OR logic

    main

    The security section is an array of maps. You can use this structure to implement complex authentication requirements using logical AND and OR:

    • OR Logic: Use separate items in the security array. Any one of these schemes can be used.
    • AND Logic: Place multiple schemes within the same map (the same array item). All schemes in that map must be provided in the request.
    • Complex Logic: Combine both by nesting maps within the array to represent (A AND B) OR (C AND D).
    # A OR B
    security:
      - A
      - B
    
    # A AND B
    security:
      - A
        B
    
    # (A AND B) OR (C AND D)
    security:
      - A
        B
      - C
        D
    
    # Example: Either basicAuth OR apiKey
    security:
      - basicAuth: []
      - apiKey: []
    
    # Example: Requires BOTH apiKey1 AND apiKey2
    security:
      - apiKey1: []
        apiKey2: []
  6. Define API operation parameters in Swagger (OAS 2.0)

    main

    In OpenAPI Specification (OAS) version 2.0, API operation parameters are defined within the parameters array under an operation definition. Each parameter requires a name and a location specified by the in key. For primitive parameters, you specify a type. For request bodies (used in POST, PUT, and PATCH), you use a schema instead of a type.

    Common parameter locations (in):

    • query: Appears after ? in the URL.
    • path: Part of the URL path (e.g., /users/{id}).
    • header: Custom HTTP headers.
    • formData: Used for application/x-www-form-urlencoded or multipart/form-data payloads.
    • body: Describes the request body (requires schema).
    paths:
      /users/{userId}:
        get:
          summary: Gets a user by ID.
          parameters:
            - in: path
              name: userId
              type: integer
              required: true
              description: Numeric ID of the user to get.
  7. Specify MIME types using consumes and produces in OpenAPI 2.0

    main

    In OpenAPI Specification version 2 (Swagger), you use the consumes and produces keywords to define the data formats your API accepts and returns.

    • consumes: An array of MIME types that the API can accept in request bodies. This only affects operations with a request body (e.g., POST, PUT, PATCH) and is ignored for bodiless operations like GET.
    • produces: An array of MIME types that the API can return in responses.

    You can define these globally at the root level of your specification to be inherited by all operations, or define them at the operation level to override the global settings.

    consumes:
      - application/json
      - application/xml
    produces:
      - application/json
      - application/xml
  8. Understand example precedence in OAS 2.0

    main

    When multiple examples are defined at different levels of the specification, tools typically follow a specific order of precedence. The higher-level example overrides lower-level ones.

    The order of precedence (from highest to lowest) is:

    1. Response example
    2. Schema example
    3. Object and array property examples
    4. Atomic property examples and array item examples
  9. Define API Paths and Operations in OpenAPI 3.0

    main

    In OpenAPI 3.0, paths represent the endpoints (resources) of your API (e.g., /users), and operations are the HTTP methods (e.g., get, post, delete) used to interact with those paths. Paths and operations are defined within the global paths section. All paths are relative to the API server URL. You can add a summary and a description (which supports Markdown) at the path level to provide context relevant to all operations under that path.

    paths:
      /users/{id}:
        summary: Represents a user
        description: >
          This resource represents an individual user in the system.
          Each user is identified by a numeric `id`.
    
        get: ...
        patch: ...
        delete: ...
  10. Define Operations (HTTP Methods)

    main

    For every path, you define one or more operations using supported HTTP methods: get, post, put, patch, delete, head, options, and trace.

    Important Uniqueness Rule: An operation is uniquely identified by the combination of its path and its HTTP method. You cannot have two GET operations on the same path, even if they use different parameters.

    paths:
      /users/{id}:
        get:
          tags:
            - Users
          summary: Gets a user by ID.
          description: >
            A detailed description of the operation.
            Use markdown for rich text representation,
            such as **bold**, *italic*, and [links](https://swagger.io).
          operationId: getUserById
          parameters:
            - name: id
              in: path
              description: User ID
              required: true
              schema:
                type: integer
                format: int64
          responses:
            "200":
              description: Successful operation
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/User"
          externalDocs:
            description: Learn more about user operations provided by this API.
            url: http://api.example.com/docs/user-operations/
  11. Use definitions for reusable input and output models

    main

    To avoid duplication, define common data structures in the global definitions section. These models can then be referenced in request bodies or response schemas using the $ref keyword.

    When defining a model, use the required keyword to list the properties that must be present in the object.

    definitions:
      User:
        properties:
          id:
            type: integer
          name:
            type: string
        required:
          - id
          - name
    
    paths:
      /users/{userId}:
        get:
          summary: Returns a user by ID.
          parameters:
            - in: path
              name: userId
              required: true
              type: integer
          responses:
            200:
              description: OK
              schema:
                $ref: "#/definitions/User"
      /users:
        post:
          summary: Creates a new user.
          parameters:
            - in: body
              name: user
              schema:
                $ref: "#/definitions/User"
          responses:
            200:
              description: OK
  12. Use media type placeholders

    main

    If you want to define a single schema that applies to a group of media types, you can use placeholders such as */*, application/*, or image/* under the content keyword.

    Note: Using a placeholder like image/* in your specification means the server uses that specific schema for all responses matching that pattern. It does not mean the literal string image/* will appear in the HTTP Content-Type header; the header will contain the specific subtype (e.g., image/png).

    paths:
      /info/logo:
        get:
          responses:
            "200":
              content:
                image/*: # Media type placeholder
                  schema:
                    type: string
                    format: binary