### Documenting Example Parameter Values Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Illustrates how to provide example values for parameters in Swagger UI, applicable to both optional and required parameters. ```ruby params do requires :id, type: Integer, documentation: { example: 123 } optional :name, type: String, documentation: { example: 'Buddy Guy' } end ``` -------------------------------- ### Response Examples JSON Structure Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Illustrates the resulting JSON structure for API responses when examples are defined using Grape-Swagger. This shows how success and failure responses, including their descriptions, schemas, and examples, are formatted. ```json { "responses": { "200": { "description": "This returns examples", "schema": { "$ref": "#/definitions/Thing" }, "examples": { "application/json": { "description": "Names list", "items": [ { "id": "123", "name": "John" } ] } } }, "404": { "description": "NotFound", "schema": { "$ref": "#/definitions/ApiError" }, "examples": { "application/json": { "code": 404, "message": "Not found" } } } } } ``` -------------------------------- ### Add Response Examples in Ruby Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how to add example data for successful and failed responses using the `desc` DSL with block syntax in Grape. This includes specifying models and providing JSON examples for different content types. ```ruby desc 'This returns examples' do success model: Thing, examples: { 'application/json' => { description: 'Names list', items: [{ id: '123', name: 'John' }] } } failure [[404, 'NotFound', ApiError, { 'application/json' => { code: 404, message: 'Not found' } }]] end get '/thing' do ... end ``` -------------------------------- ### Example JSON Response Structure Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Illustrates the resulting JSON structure for documented responses, showing how status codes, descriptions, and schema references are represented. ```json "responses": { "200": { "description": "get Horses", "schema": { "$ref": "#/definitions/Thing" } }, "401": { "description": "HorsesOutError", "schema": { "$ref": "#/definitions/ApiError" } } }, ``` ```json "responses": { "202": { "description": "ok", "schema": { "$ref": "#/definitions/UseResponse" } } }, ``` -------------------------------- ### Install grape-swagger Gem Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Add the grape-swagger gem to your Gemfile to include its functionality in your Ruby project. ```ruby gem 'grape-swagger' ``` -------------------------------- ### Customizing Swagger Endpoint Parameters Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This example shows how to customize various aspects of the Swagger documentation, such as the host, base path, mount path, and information about the API. It also covers how to handle authentication and define models. ```Ruby add_swagger_documentation( host: 'localhost:3000', base_path: '/api/v1', mount_path: '/swagger_doc', add_base_path: false, add_root: true, add_version: true, doc_version: '1.0', endpoint_auth_wrapper: nil, swagger_endpoint_guard: nil, token_owner: nil, security_definitions: { api_key: { type: 'apiKey', name: 'Authorization', in: 'header' } }, security: [ { api_key: [] } ], models: [], tags: [ { name: 'users', description: 'Operations about users' } ], hide_documentation_path: false, info: { title: 'My API', description: 'A sample API', license: 'MIT', license_url: 'https://example.com/license' }, array_use_braces: false ) ``` -------------------------------- ### Mount Grape API with Swagger Documentation Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Include `add_swagger_documentation` in your root Grape API class to enable Swagger documentation generation at '/swagger_doc'. This example mounts Cats, Dogs, and Pirates APIs. ```ruby require 'grape-swagger' module API class Root < Grape::API format :json mount API::Cats mount API::Dogs mount API::Pirates add_swagger_documentation end end ``` -------------------------------- ### Group API Endpoints by Namespace Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Organizes API endpoints into logical groups using namespaces. This example shows how to define a namespace for 'hudson' and 'download' with associated descriptions and HTTP methods. ```ruby class NamespaceApi < Grape::API namespace :hudson do desc 'Document root' get '/' do end desc 'This gets something.', detail: '_test_' get '/simple' do { bla: 'something' } end end namespace :download do desc 'download files', success: File, produces: ['text/csv'] get ':id' do # file response end end end … ``` -------------------------------- ### Response Documentation in Grape Swagger Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This snippet demonstrates how to document API responses in Grape Swagger, including setting default status codes, multiple status codes, file responses, default responses, extensions, and response examples. ```Ruby # Default response documentation get '/resource' do { message: 'Success' } end # Changing default status codes get '/resource', success: 201 do { message: 'Created' } end # Multiple status codes for response get '/items/:id', http_methods: ['GET'], success: { code: 200, message: 'Item found', entity: API::Entities::Item }, failure: { code: 404, message: 'Item not found' } do # ... end # File response get '/download' do content_type 'application/octet-stream' env['api.response'] = File.open('path/to/file.zip', 'rb') end # Response examples documentation get '/example_response' do # ... end get '/example_response', response: { 200 => { description: 'Successful response', examples: { 'application/json' => { 'data' => 'example' } } } } # Response headers documentation get '/headers' do # ... end get '/headers', headers: { 'X-RateLimit-Limit' => { type: Integer, description: 'The number of allowed requests in the current period' } } # Adding root element to responses get '/users', root: 'users' do [{ id: 1 }, { id: 2 }] end # Multiple present Response get '/complex_response' do present :user, User.new, entity: API::Entities::User present :posts, Post.all, entity: API::Entities::Post, type: :list end ``` -------------------------------- ### Securing the Swagger UI Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This example demonstrates how to secure the Swagger UI endpoint by implementing a guard. The `swagger_endpoint_guard` option can be used to provide a Proc that will be called before rendering the Swagger UI. ```Ruby class API::Base < Grape::API # ... other configurations ... # Secure the Swagger UI with a guard add_swagger_documentation( # ... other options ... swagger_endpoint_guard: ->(request) { request.headers['X-API-KEY'] == 'your-secret-key' } ) end ``` -------------------------------- ### Validate OpenApi/Swagger Documentation Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Shows how to validate OpenApi/Swagger documentation using a Rake task. Requires npm and swagger-cli to be installed. Allows filtering validation by resource name. ```bash rake oapi:validate params: - resource=resource_name – get only for this one (optional) ``` -------------------------------- ### Implement Polymorphic Inheritance with allOf and Discriminator Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This example illustrates how to implement polymorphic inheritance in Grape entities using `allOf` and a discriminator. It defines a base `Pet` entity with a `type` discriminator and a `Cat` entity inheriting from `Pet`, showcasing detailed documentation for properties, defaults, and enumerated values. ```ruby module Entities class Pet < Grape::Entity expose :type, documentation: { type: 'string', is_discriminator: true, required: true } expose :name, documentation: { type: 'string', required: true } end class Cat < Pet expose :huntingSkill, documentation: { type: 'string', description: 'The measured skill for hunting', default: 'lazy', values: %w[ clueless lazy adventurous aggressive ] } end end ``` -------------------------------- ### Grouping API List using Namespace Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This snippet shows how to group API endpoints by namespace in the Swagger UI. By default, Grape Swagger uses the Grape namespace to group endpoints. This example explicitly shows how this grouping occurs. ```Ruby module API class V1 < Grape::API version 'v1' format :json resource :users do desc 'Return a list of users' get do [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] end end end class V2 < Grape::API version 'v2' format :json resource :products do desc 'Return a list of products' get do [{ id: 101, name: 'Laptop' }, { id: 102, name: 'Mouse' }] end end end end class API::Base < Grape::API mount API::V1 mount API::V2 add_swagger_documentation( api_version: 'v1', base_path: '/api', hide_documentation_path: true ) end ``` -------------------------------- ### Fetch OpenApi/Swagger Documentation Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how to fetch OpenApi/Swagger documentation using a Rake task. It includes parameters for saving the output to a JSON file and filtering by resource name. Supports multi-version APIs by creating versioned files. ```bash rake oapi:fetch params: - store={ true | file_name.json } – save as JSON (optional) - resource=resource_name – get only for this one (optional) ``` -------------------------------- ### Configure mount_path Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Specifies the path where the API documentation will be mounted. The default path is '/swagger_doc'. ```ruby add_swagger_documentation \ mount_path: '/swagger_doc' ``` -------------------------------- ### Configure Grape-Swagger Documentation Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Configures Grape-Swagger documentation with options for base path, title, version, hiding documentation path, and specifying authentication middleware and guards. ```ruby add_swagger_documentation base_path: '/', title: 'My API', doc_version: '0.0.1', hide_documentation_path: true, endpoint_auth_wrapper: WineBouncer::OAuth2, # This is the middleware for securing the Swagger UI swagger_endpoint_guard: 'oauth2 false', # this is the guard method and scope token_owner: 'resource_owner' # This is the method returning the owner of the token ``` -------------------------------- ### Configure base_path Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Sets the base path for the API documentation. If not provided, it defaults to nil, and the base path is taken from the request. ```ruby add_swagger_documentation \ base_path: nil ``` -------------------------------- ### Documenting Response Status Codes and Models Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Provides various syntaxes for documenting HTTP status codes, including descriptions and model references, for API responses. ```ruby desc 'thing', failure: [ { code: 400, message: 'Invalid parameter entry' } ] get '/thing' do # ... end ``` ```ruby desc 'thing' do params Entities::Something.documentation failure [ { code: 400, message: 'Invalid parameter entry' } ] end get '/thing' do # ... end ``` ```ruby get '/thing', failure: [ { code: 400, message: 'Invalid parameter entry' }, { code: 404, message: 'Not authorized' }, ] do # ... end ``` ```ruby get '/thing', failure: [ { code: 400, message: 'General error' }, { code: 403, message: 'Forbidden error', model: '' }, { code: 422, message: 'Invalid parameter entry', model: Entities::ApiError } ] do # ... end ``` -------------------------------- ### Grape API with Swagger Integration Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This snippet demonstrates how to mount the GrapeSwagger::Endpoint to an existing Grape API, enabling Swagger documentation generation. It includes basic configuration options like the API version and host. ```Ruby require 'grape-swagger' module API class Base < Grape::API format :json # Mount the Swagger endpoint mount GrapeSwagger::Endpoint # Configure Swagger options swagger_root = File.expand_path('../swagger_root', __FILE__) add_swagger_documentation( api_version: 'v1', base_path: '/api', hide_documentation_path: true, swagger_root: swagger_root ) # Define your API resources here # ... end end ``` -------------------------------- ### Grape Entity Documentation (Ruby) Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Shows how to document Grape Entities with details like type, description, and required status for each exposed attribute. It also illustrates how to define entity names for Swagger documentation. ```ruby module API module Entities class Status < Grape::Entity expose :text, documentation: { type: 'string', desc: 'Status update text.', required: true } expose :links, using: Link, documentation: { type: 'link', is_array: true } expose :numbers, documentation: { type: 'integer', desc: 'favourite number', values: [1,2,3,4] } end class Link < Grape::Entity expose :href, documentation: { type: 'url' } expose :rel, documentation: { type: 'string'} def self.entity_name 'LinkedStatus' end end end class Statuses < Grape::API version 'v1' desc 'Statuses index', entity: API::Entities::Status get '/statuses' do statuses = Status.all type = current_user.admin? ? :full : :default present statuses, with: API::Entities::Status, type: type end desc 'Creates a new status', entity: API::Entities::Status, params: API::Entities::Status.documentation post '/statuses' do ... end end end ``` ```ruby module API module Entities class Status < Grape::Entity expose :text, documentation: { type: 'string', desc: 'Status update text.', required: true } end class Link < Grape::Entity expose :href, documentation: { type: 'url' } def self.entity_name 'LinkedStatus' end end end end ``` -------------------------------- ### Add Response Headers in Ruby Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Shows how to document response headers for both successful and failed API calls using the `desc` DSL in Grape. This includes specifying header details like description and type. ```ruby desc 'This returns headers' do success model: Thing, headers: { 'Location' => { description: 'Location of resource', type: 'string' } } failure [[404, 'NotFound', ApiError, { 'application/json' => { code: 404, message: 'Not found' } }, { 'Date' => { description: 'Date of failure', type: 'string' } }]] end get '/thing' do ... end ``` -------------------------------- ### Grape Swagger: Handle Multiple Parameter Types Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how Grape handles parameters with multiple specified types, defaulting to the first type listed. ```ruby params do requires :action, types: [String, Integer] end post :act do ... end ``` -------------------------------- ### Configure host Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Sets an explicit host for the API documentation. If not provided, the host is taken from the request object. ```ruby add_swagger_documentation \ host: 'www.example.com' ``` -------------------------------- ### Configure base_path with Proc Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Dynamically sets the base path for the API documentation using a proc or lambda, which evaluates based on the incoming request object. This allows for environment-specific base paths. ```ruby add_swagger_documentation \ base_path: proc { |request| request.host =~ /^example/ ? '/api-example' : '/api' } ``` -------------------------------- ### Configure add_version Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Controls the inclusion of the 'version' key in documented path keys. Defaults to true, using the API version specified in Grape's path. ```ruby add_swagger_documentation \ add_version: true ``` -------------------------------- ### Document Swagger Header Parameters Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how to document parameters passed in the header for Swagger API documentation using Grape. It specifies header names, their descriptions, and whether they are required. ```ruby desc "Return super-secret information", { headers: { "XAuthToken" => { description: "Valdates your identity", required: true }, "XOptionalHeader" => { description: "Not really needed", required: false } } } ``` -------------------------------- ### Grape Swagger: Use Options Hash for Settings Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates using an options hash in Grape to pass settings like 'hidden', 'is_array', 'nickname', 'success', 'failure', 'produces', and 'consumes' for API endpoint documentation. ```ruby desc 'Get all kittens!', { hidden: true, is_array: true, nickname: 'getKittens', success: Entities::Kitten, # or success failure: [[401, 'KittenBitesError', Entities::BadKitten]] # or failure # also explicit as hash: [{ code: 401, message: 'KittenBitesError', model: Entities::BadKitten }] produces: [ "array", "of", "mime_types" ], consumes: [ "array", "of", "mime_types" ] } get '/kittens' do ``` -------------------------------- ### Initialize Grape-Swagger Rake Tasks Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Initializes Grape-Swagger Rake tasks for OpenApi/Swagger generation. It shows how to require the task class and initialize it with the API class, either directly or as a string. ```ruby require 'grape-swagger/rake/oapi_tasks' GrapeSwagger::Rake::OapiTasks.new(::Api::Base) ``` ```ruby require 'grape-swagger/rake/oapi_tasks' GrapeSwagger::Rake::OapiTasks.new('::Api::Base') ``` -------------------------------- ### Using Grape Entities for Model Documentation Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This snippet shows how to integrate Grape Entities with grape-swagger to document API models. It covers documenting classes/definitions, defining relationships (1xN, 1x1), and handling inheritance with `allOf` and `discriminator`. ```Ruby require 'grape-entity' module API module Entities class User < Grape::Entity expose :id expose :name expose :email end class Post < Grape::Entity expose :id expose :title expose :body expose :user, using: User # 1x1 relationship end class UserWithPosts < Grape::Entity expose :id expose :name expose :posts, using: Post, type: :list # 1xN relationship end class Animal < Grape::Entity expose :species end class Dog < Animal expose :breed end class Cat < Animal expose :color end end end class API::Base < Grape::API # ... other configurations ... # Documenting a class/definition get '/users/:id', entity: API::Entities::User # Documenting relationships get '/user_with_posts/:id', entity: API::Entities::UserWithPosts # Inheritance with allOf and discriminator get '/animals/:id', entity: API::Entities::Animal, discriminator: { fieldName: 'species', mapping: { 'dog' => API::Entities::Dog, 'cat' => API::Entities::Cat } } end ``` -------------------------------- ### Configure doc_version Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Sets the version for the documentation itself, as specified in the OpenAPI Specification's info section. Defaults to '0.0.1'. ```ruby add_swagger_documentation \ doc_version: '0.0.1' ``` -------------------------------- ### Define API Entities with Grape Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This snippet demonstrates how to define API entities using Grape, including basic string exposure and nested entities with documentation attributes. It also shows how to set up a Grape API endpoint with versioning and documentation. ```ruby module API module Entities class Client < Grape::Entity expose :name, documentation: { type: 'string', desc: 'Name' } expose :address, using: Entities::Address, documentation: { type: 'Entities::Address', desc: 'Addresses.', param_type: 'body', is_array: false } end class Address < Grape::Entity expose :street, documentation: { type: 'string', desc: 'Street' } end end class Clients < Grape::API version 'v1' desc 'Clients index', params: Entities::Client.documentation, success: Entities::Client get '/clients' do ... end end add_swagger_documentation end ``` -------------------------------- ### Configure API Info Object Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Merges a hash into the 'info' key of the Swagger JSON documentation, allowing customization of title, description, contact details, and license information. ```ruby add_swagger_documentation \ info: { title: "The API title to be displayed on the API homepage.", description: "A description of the API.", contact_name: "Contact name", contact_email: "Contact@email.com", contact_url: "Contact URL", license: "The name of the license.", license_url: "www.The-URL-of-the-license.org", terms_of_service_url: "www.The-URL-of-the-terms-and-service.com" } ``` -------------------------------- ### Specify Endpoint Details in Swagger Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Illustrates how to provide more detailed information for an API endpoint in Swagger documentation using the `detail` option within a block passed to the `desc` method in Grape. ```ruby desc 'Get all kittens!' do detail 'this will expose all the kittens' end get '/kittens' do ``` -------------------------------- ### Grape Swagger: JSON for Multiple Parameter Types Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Shows the JSON output for a Grape parameter configured with multiple types, where the first type (String) is selected as the Swagger type. ```json { "in": "formData", "name": "action", "type": "string", "required": true } ``` -------------------------------- ### Ruby: Add Swagger Extensions to API Documentation Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This Ruby code illustrates how to add custom extensions to Swagger documentation at various levels (root, info, verb, path, definition, params) using Grape-Swagger. Extensions are defined using keys prefixed with 'x-'. ```ruby add_swagger_documentation \ x: { some: 'stuff' }, info: { } ``` ```ruby add_swagger_documentation \ info: { x: { some: 'stuff' } } ``` ```ruby desc 'This returns something with extension on verb level', x: { some: 'stuff' } ``` ```ruby route_setting :x_operation, { some: 'stuff' } ``` ```ruby route_setting :x_path, { some: 'stuff' } ``` ```ruby route_setting :x_def, { for: 422, other: 'stuff' } ``` ```ruby route_setting :x_def, [{ for: 422, other: 'stuff' }, { for: 200, some: 'stuff' }] ``` ```ruby requires :foo, type: String, documentation: { x: { some: 'stuff' } } ``` -------------------------------- ### Ruby: Configure File Response with Default Content Type Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This Ruby snippet shows how to configure a file response in Grape-Swagger. Setting `success` to `File` automatically sets the `produces` attribute to `application/octet-stream`, indicating a binary file download. ```ruby desc 'Get a file', success: File get do # your file response end ``` -------------------------------- ### Rake Tasks for OpenAPI/Swagger Documentation Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This section describes the Rake tasks provided by grape-swagger for generating and validating OpenAPI/Swagger documentation. These tasks are useful for CI/CD pipelines and local development workflows. ```Ruby # Generate OpenAPI/Swagger documentation # Usage: rake swagger:docs # Validate OpenAPI/Swagger documentation # Usage: rake swagger:validate ``` -------------------------------- ### Configure add_base_path Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Determines whether to include the 'basePath' key in the documented path keys. Defaults to false, but can be set to true if a base_path is provided. ```ruby add_swagger_documentation \ add_base_path: true # only if base_path given ``` -------------------------------- ### Customize Specific API Documentation Route Description Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Allows customization of the description for the Swagger API specific documentation route. The default description is 'Swagger compatible API description for specific API'. ```ruby add_swagger_documentation \ specific_api_documentation: { desc: 'Reticulated splines API swagger-compatible endpoint documentation.' } ``` -------------------------------- ### Configure Security Definitions for API Key Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Specifies security definitions for the API, such as API key authentication. This uses the OpenAPI Security Definitions Object. ```ruby add_swagger_documentation \ security_definitions: { api_key: { type: "apiKey", name: "api_key", in: "header" } } ``` -------------------------------- ### Configure Global Produces Field Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Sets the default global `produces` field value for the Swagger API documentation, specifying the media types the API can produce. ```ruby add_swagger_documentation \ produces: ['text/plain'] ``` -------------------------------- ### Customize API Documentation Route Description Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Allows customization of the description for the Swagger API documentation route. The default description is 'Swagger compatible API description'. ```ruby add_swagger_documentation \ api_documentation: { desc: 'Reticulated splines API swagger-compatible documentation.' } ``` -------------------------------- ### Specify Custom Multiple Response (Ruby) Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how to define a custom multiple response in Grape Swagger using the 'as' key to map different models to specific response keys. It also shows how to specify if a response is an array using 'is_array'. ```ruby desc 'Multiple response', success: [ { model: Entities::EnumValues, as: :gender }, { model: Entities::Something, as: :somethings } ] end get '/things' do ... end ``` ```ruby desc 'Multiple response with array', success: [ { model: Entities::EnumValues, as: :gender }, { model: Entities::Something, as: :somethings, is_array: true, required: true } ] end get '/things' do ... end ``` -------------------------------- ### Expose Nested Namespace as Standalone Route Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Explains how to use `nested: false` in Grape-Swagger to expose nested namespaces as standalone routes, simplifying the Swagger schema structure. ```ruby namespace 'store/order', desc: 'Order operations within a store', swagger: { nested: false } do get :order_id do ... end end ``` -------------------------------- ### Grape Entity Relationships (Ruby) Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how to define relationships between Grape Entities, including one-to-many (1xN) relationships, and how to document them for Swagger. It shows omitting 'type' when it can be inferred and specifying it when needed. ```ruby module API module Entities class Client < Grape::Entity expose :name, documentation: { type: 'string', desc: 'Name' } expose :addresses, using: Entities::Address, documentation: { type: 'Entities::Address', desc: 'Addresses.', param_type: 'body', is_array: true } end class Address < Grape::Entity expose :street, documentation: { type: 'string', desc: 'Street.' } end end class Clients < Grape::API version 'v1' desc 'Clients index', params: Entities::Client.documentation, success: Entities::Client get '/clients' do ... end end add_swagger_documentation end ``` -------------------------------- ### Configure endpoint_auth_wrapper Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Specifies the middleware to be used for securing API endpoints, such as for OAuth2 authentication. ```ruby add_swagger_documentation \ endpoint_auth_wrapper: WineBouncer::OAuth2 ``` -------------------------------- ### Swagger Definitions for Grape Entities (JSON) Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Illustrates the resulting Swagger JSON definitions for Grape Entities, including object properties, types, descriptions, and required fields, as well as custom entity names. ```json { "definitions": { "API_Entities_Status": { "type": "object", "properties": { "text": { "type": "string", "description": "Status update text." } }, "required": [ "text" ], "description": "API_Entities_Pet model" }, "LinkedStatus": { "type": "object", "properties": { "href": { "type": "url" } }, "description": "LinkedStatus model" } } } ``` -------------------------------- ### Document API Models with Grape Entity Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Provides a list of entities to document, typically used in conjunction with the grape-entity gem. These models are added to the 'definitions' section of the Swagger file. ```ruby add_swagger_documentation \ models: [ TheApi::Entities::UseResponse, TheApi::Entities::ApiError ] ``` -------------------------------- ### Allow Additional Properties Matching a Defined Schema Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Shows how to permit additional properties that conform to a defined Grape Entity schema using `additional_properties`. ```ruby class Entity < Grape::Entity expose :this end params do optional :thing, type: Hash, documentation: { additional_properties: Entity } end ``` -------------------------------- ### Configure Array Submission Format Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Determines how array parameters are submitted. When `true`, elements are submitted with `[]`, ensuring proper handling of Array types. When `false`, elements are submitted with the same key, which can lead to issues. ```ruby add_swagger_documentation \ array_use_braces: true ``` -------------------------------- ### Document API Tags Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Specifies a list of tags for organizing API endpoints. Tags are usually generated automatically based on route names, but can be customized. ```ruby add_swagger_documentation \ tags: [ { name: 'widgets', description: 'A description of widgets' } ] ``` -------------------------------- ### Ruby: Define Default Response for Unspecified Status Codes Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This Ruby code demonstrates how to define a default response in Grape-Swagger that applies to all unspecified status codes. It shows how to provide a simple message or a model reference for the default response. ```ruby desc 'thing', default: { message: 'the default response' } get '/thing' do # ... end ``` ```ruby desc 'Get a list of stuff', default: { model: Entities::UseResponse, message: 'the default response' } get do # your code comes here end ``` -------------------------------- ### JSON: Swagger Specification for Default Response Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This JSON snippet shows the Swagger representation of a default response. It includes a `default` key within the `responses` object, specifying a description and optionally a schema reference for the default response. ```json "responses": { "default": { "description": "the default response" } }, ``` ```json "responses": { "default": { "description": "the default response", "schema": { "$ref": "#/definitions/UseResponse" } } }, ``` -------------------------------- ### Grape Swagger: Set Default Value for Parameter Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Illustrates setting a default value for a parameter in Grape using the 'documentation' hash, which influences the Swagger UI's 'defaultValue'. ```ruby params do requires :id, type: Integer, desc: 'Coffee ID' requires :temperature, type: Integer, desc: 'Temperature of the coffee in celcius', documentation: { default: 72 } end ``` -------------------------------- ### Response Headers JSON Structure Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Presents the JSON output for API responses when header information is documented using Grape-Swagger. This details how headers are structured within the success and failure response objects. ```json { "responses": { "200": { "description": "This returns examples", "schema": { "$ref": "#/definitions/Thing" }, "headers": { "Location": { "description": "Location of resource", "type": "string" } } }, "404": { "description": "NotFound", "schema": { "$ref": "#/definitions/ApiError" }, "examples": { "application/json": { "code": 404, "message": "Not found" } }, "headers": { "Date": { "description": "Date of failure", "type": "string" } } } } } ``` -------------------------------- ### Enable CORS with Rack-Cors Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Configures Cross-Origin Resource Sharing (CORS) using the rack-cors gem. This allows requests from different origins to access the API. ```ruby require 'rack/cors' use Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: [ :get, :post, :put, :delete, :options ] end end ``` -------------------------------- ### Add Grape Swagger Representable Gem Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Include the `grape-swagger-representable` gem in your Gemfile to add support for representable, a serialization library. ```ruby gem 'grape-swagger-representable', '~> 0.2' ``` -------------------------------- ### Grape Swagger: JSON for Array Collection Format Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Shows the JSON output for a Grape parameter with an array type and a specified collection format ('multi'), detailing its structure. ```json { "in": "formData", "name": "statuses", "type": "array", "items": { "type": "string" }, "collectionFormat": "multi", "required": true } ``` -------------------------------- ### Override Route Summary in Swagger Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how to override the default summary for a route in Swagger documentation by adding the `summary: '[string]'` option after the main description in Grape. ```ruby namespace 'order' do desc 'This will be your summary', summary: 'Now this is your summary!' get :order_id do ... end end ``` -------------------------------- ### Setting Additional Properties for Object-Type Parameters Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md This section details how to configure `additionalProperties` for object-type parameters in Swagger, allowing for flexible schema definitions. It covers allowing any properties, properties of a specific type, or properties matching a defined schema. ```Ruby # Allow any additional properties params: { user: { type: Object, additional_properties: true, description: 'User object with any properties' } } # Allow any additional properties of a particular type params: { settings: { type: Object, additional_properties: { type: String }, description: 'Settings object with string properties' } } # Allow any additional properties matching a defined schema params: { data: { type: Object, additional_properties: { '$ref': '#/definitions/MySchema' }, description: 'Data object with properties matching MySchema' } } ``` -------------------------------- ### Define Endpoint as Array in Swagger Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Illustrates how to define an API endpoint that returns an array in Swagger documentation by adding the `is_array: true` option to the `desc` method in Grape. ```ruby desc 'Get a full list of pets', is_array: true ``` -------------------------------- ### JSON: Swagger Specification with Extensions Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md These JSON snippets demonstrate how custom extensions are represented in the Swagger specification. They show extensions applied to the root object, info object, verb level, path level, definitions, and parameters, all prefixed with 'x-'. ```json { "x-some": "stuff", "info":{ } } ``` ```json "info":{ "x-some":"stuff" } ``` ```json "/path":{ "get":{ "…":"…", "x-some":"stuff" } } ``` ```json "/path":{ "get":{ "…":"…", "x-some":"stuff" } } ``` ```json "/path":{ "x-some":"stuff", "get":{ "…":"…", } } ``` ```json "/definitions":{ "ApiError":{ "x-other":"stuff", "…":"…", } } ``` ```json { "in": "formData", "name": "foo", "type": "string", "required": true, "x-some": "stuff" } ``` -------------------------------- ### Enable CORS with Grape Before Block Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Enables CORS by setting Access-Control-Allow-Origin and Access-Control-Request-Method headers within a Grape 'before' block. This is an alternative to using rack-cors. ```ruby before do header['Access-Control-Allow-Origin'] = '*' header['Access-Control-Request-Method'] = '*' end ``` -------------------------------- ### Grape Swagger: Allow Additional Properties for Object Type Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates using the 'additional_properties' option in Grape's documentation hash to allow any additional properties for object-type parameters, aligning with Swagger's map/dictionary format. ```ruby params do optional :thing, type: Hash, documentation: { additional_properties: true } end ``` -------------------------------- ### Grape Swagger: Set Array Collection Format Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates setting the 'collectionFormat' for an array parameter in Grape, specifying how array values should be formatted (e.g., 'multi'). ```ruby params do requires :statuses, type: Array[String], documentation: { collectionFormat: 'multi' } end post :act do ... end ``` -------------------------------- ### Allow Additional Properties of a Specific Type Source: https://github.com/ruby-grape/grape-swagger/blob/master/README.md Demonstrates how to allow any additional properties of a specific type within a parameter using `additional_properties` in Grape-Swagger documentation. ```ruby params do optional :thing, type: Hash, documentation: { additional_properties: String } end ```