Swagger::Blocks

repository·master·Indexed 20 days ago

https://github.com/fotinakis/swagger-blocks

A Ruby DSL for defining Swagger 2.0 and OpenAPI 3.0 API specifications directly in Ruby code. It allows developers to generate JSON documentation dynamically, ensuring API docs remain in sync with the code. The library is framework-agnostic, working with Rails, Sinatra, or plain Ruby objects, and provides methods like swagger_path, swagger_schema, and swagger_root to map Ruby blocks to the Swagger specification.

Tokens
6.9K
Snippets
30
Records
37
Agent score
70%

What's inside swagger-blocks

  1. How Swagger::Blocks works

    master

    Swagger::Blocks is a DSL that allows you to write API documentation in pure Ruby code blocks. These blocks are then converted into JSON compatible with the Swagger 2.0 specification and Swagger UI.

    Key characteristics:

    • Live Updating: Changes to your Ruby code are reflected in your API docs upon refresh.
    • Framework Agnostic: Works with Rails, Sinatra, or even plain Ruby objects.
    • 1:1 Mapping: The DSL block names and nesting closely follow the Swagger spec structure.
  2. Swagger version compatibility

    master

    Swagger 2.0

    This is the primary supported version for swagger-blocks >= 2.0.0.

    Swagger 1.2

    Support for the Swagger 1.2 spec was dropped in version 2.0.0. If your project requires Swagger 1.2 support, you must use version 1.4.0 of the gem.

  3. Serve Swagger JSON via a Docs Controller

    master

    To make your documentation accessible to Swagger UI, create a controller that uses swagger_root to define the global API metadata and Swagger::Blocks.build_root_json to generate the full JSON object.

    Crucial Step: You must pass an array of all classes containing swagger_* declarations to build_root_json. If you are defining the root in the same controller that serves the JSON, include self in that array.

    class ApidocsController < ActionController::Base
      include Swagger::Blocks
    
      swagger_root do
        key :swagger, '2.0'
        info do
          key :title, 'Swagger Petstore'
          key :version, '1.0.0'
        end
        key :host, 'petstore.swagger.wordnik.com'
        key :basePath, '/api'
      end
    
      # Include all classes that have swagger declarations
      SWAGGERED_CLASSES = [
        PetsController,
        Pet,
        ErrorModel,
        self,
      ].freeze
    
      def index
        render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
      end
    end
  4. Reduce boilerplate with reusable response modules

    master

    For common responses (like 401 Unauthorized or 404 Not Found), you can create a Ruby module that uses self.extended(base) to inject response blocks into an operation.

    module SwaggerResponses
      module AuthenticationError
        def self.extended(base)
          base.response 401 do
            key :description, 'not authorized'
            schema do
              key :'$ref', :AuthenticationError
            end
          end
        end
      end
    end
    
    # Usage in a controller
    operation :post do
      extend SwaggerResponses::AuthenticationError
    end
  5. Use inline keys to reduce boilerplate

    master

    You can pass configuration keys directly as arguments to DSL methods (like parameter) to avoid multiple key calls. This is equivalent to using the key method inside a block.

    # Using inline keys
    parameter paramType: :path, name: :petId, type: :string do
      key :description, 'ID of pet that needs to be fetched'
    end
  6. Reference reusable parameters

    master

    Instead of redefining the same parameters in multiple operations, you can define them once in the swagger_root and reference them by name within swagger_path or operation nodes.

    swagger_root do
      parameter :species do
        key :name, :species
        key :description, 'Species of this pet'
      end
    end
    
    swagger_path '/pets/' do
      operation :post do
        parameter :species
      end
    end
  7. Define API paths and operations

    master

    To document endpoints, include Swagger::Blocks in your controller and use swagger_path to define routes. Inside a path, use operation to define HTTP methods (e.g., :get, :post).

    Common DSL methods used within an operation:

    • key: Sets a specific key/value pair in the resulting JSON.
    • parameter: Defines an input parameter (path, query, body, etc.).
    • response: Defines a response (e.g., response 200 or response :default).
    • schema: Defines the data structure for a response or parameter.
    class PetsController < ActionController::Base
      include Swagger::Blocks
    
      swagger_path '/pets/{id}' do
        operation :get do
          key :summary, 'Find Pet by ID'
          parameter do
            key :name, :id
            key :in, :path
            key :type, :integer
          end
          response 200 do
            key :description, 'pet response'
            schema do
              key :'$ref', :Pet
            end
          end
        end
      end
    end
  8. Define reusable Models with swagger_schema

    master

    You can define data models (schemas) by using swagger_schema within a class. This allows you to reference these models in your paths using '$ref'.

    class Pet < ActiveRecord::Base
      include Swagger::Blocks
    
      swagger_schema :Pet do
        key :required, [:id, :name]
        property :id do
          key :type, :integer
          key :format, :int64
        end
        property :name do
          key :type, :string
        end
      end
    end
  9. Configure Security Definitions and Requirements

    master

    To support API key or OAuth2 authentication, define security_definition blocks within your swagger_root. You can then apply these to the entire API or to specific operations using the security block.

    # In swagger_root
    security_definition :api_key do
      key :type, :apiKey
      key :name, :api_key
      key :in, :header
    end
    
    # In an operation
    operation :get do
      security do
        key :api_key, []
      end
    end
  10. Reference complex Swagger declarations

    master

    For examples of complex features and advanced Swagger 2.0 declarations, refer to the project's specification test file. This is the most authoritative source for seeing how nested structures and advanced schema features are implemented using swagger_blocks syntax.

    https://github.com/fotinakis/swagger-blocks/blob/master/spec/lib/swagger_v2_blocks_spec.rb
  11. Define Swagger paths with `swagger_path`

    master

    Use swagger_path(path, &block) to define a Swagger Path Item object. If you call swagger_path multiple times with the same path, the library will merge the subsequent declarations into the existing path node. This allows you to spread path definitions across different parts of your code.

    # First declaration
    swagger_path '/users' do
      get 'Returns all users'
    end
    
    # Subsequent declaration (merges into '/users')
    swagger_path '/users' do
      post 'Creates a user'
    end