Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add OAPI/swagger v2.0 compliant documentation to your grape API

License

NotificationsYou must be signed in to change notification settings

ruby-grape/grape-swagger

Repository files navigation

Gem VersionBuild StatusCoverage StatusCode Climate

Table of Contents

What is grape-swagger?

The grape-swagger gem provides an autogenerated documentation for yourGrape API. The generated documentation is Swagger-compliant, meaning it can easily be discovered inSwagger UI. You should be able to pointthe petstore demo to your API.

Demo Screenshot

This screenshot is based on theHussars sample app.

Related Projects

Compatibility

The following versions of grape, grape-entity and grape-swagger can currently be used together.

grape-swaggerswagger specgrapegrape-entityrepresentable
0.10.51.2>= 0.10.0 ... <= 0.14.0< 0.5.0n/a
0.11.01.2>= 0.16.2< 0.5.0n/a
0.25.22.0>= 0.14.0 ... <= 0.18.0<= 0.6.0>= 2.4.1
0.26.02.0>= 0.16.2 ... <= 1.1.0<= 0.6.1>= 2.4.1
0.27.02.0>= 0.16.2 ... <= 1.1.0>= 0.5.0>= 2.4.1
0.32.02.0>= 0.16.2>= 0.5.0>= 2.4.1
0.34.02.0>= 0.16.2 ... < 1.3.0>= 0.5.0>= 2.4.1
>= 1.0.02.0>= 1.3.0>= 0.5.0>= 2.4.1
>= 2.0.02.0>= 1.7.0>= 0.5.0>= 2.4.1
>= 2.0.0 ... < 2.22.0>= 1.8.0 ... < 2.3.0>= 0.5.0>= 2.4.1

Swagger-Spec

Grape-swagger generates documentation perSwagger / OpenAPI Spec 2.0.

Installation

Add to your Gemfile:

gem'grape-swagger'

Upgrade

Please seeUPGRADING when upgrading from a previous version.

Usage

Mount all your different APIs (withGrape::API superclass) on a root node. In the root class definition, includeadd_swagger_documentation, this sets up the system and registers the documentation on '/swagger_doc'. Seeexample/config.ru for a simple demo.

require'grape-swagger'moduleAPIclassRoot <Grape::APIformat:jsonmountAPI::CatsmountAPI::DogsmountAPI::Piratesadd_swagger_documentationendend

To explore your API, either downloadSwagger UI and set it up yourself or go to theonline swagger demo and enter your localhost url documentation root in the url field (probably something in the line ofhttp://localhost:3000/swagger_doc).

Model Parsers

Since 0.21.0,Grape::Entity is not a part of grape-swagger, you need to addgrape-swagger-entity manually to your Gemfile.Also added support forrepresentable viagrape-swagger-representable.

# For Grape::Entity ( https://github.com/ruby-grape/grape-entity )gem'grape-swagger-entity','~> 0.3'# For representable ( https://github.com/apotonick/representable )gem'grape-swagger-representable','~> 0.2'

If you are not using Rails, make sure to load the parser inside your application initialization logic, e.g., viarequire 'grape-swagger/entity' orrequire 'grape-swagger/representable'.

Custom Model Parsers

You can create your own model parser, for example forroar.

moduleGrapeSwaggermoduleRoarclassParserattr_reader:modelattr_reader:endpointdefinitialize(model,endpoint)@model=model@endpoint=endpointenddefcall# Parse your model and return hash with model schema for swaggerendendendend

Then you should register your custom parser.

GrapeSwagger.model_parsers.register(GrapeSwagger::Roar::Parser,Roar::Decorator)

To control model parsers sequence, you can insert your parser before or after another parser.

insert_before

GrapeSwagger.model_parsers.insert_before(GrapeSwagger::Representable::Parser,GrapeSwagger::Roar::Parser,Roar::Decorator)

insert_after

GrapeSwagger.model_parsers.insert_after(GrapeSwagger::Roar::Parser,GrapeSwagger::Representable::Parser,Representable::Decorator)

As we know,Roar::Decorator usesRepresentable::Decorator as a superclass, this allows to avoid a problem when Roar objects are processed byGrapeSwagger::Representable::Parser instead ofGrapeSwagger::Roar::Parser.

CORS

If you use the online demo, make sure your API supports foreign requests by enabling CORS in Grape, otherwise you'll see the API description, but requests on the API won't return. Userack-cors to enable CORS.

require'rack/cors'useRack::Corsdoallowdoorigins'*'resource'*',headers::any,methods:[:get,:post,:put,:delete,:options]endend

Alternatively you can set CORS headers in a Grapebefore block.

beforedoheader['Access-Control-Allow-Origin']='*'header['Access-Control-Request-Method']='*'end

Configure

You can pass a hash with optional configuration settings toadd_swagger_documentation.The examples show the default value.

Thehost andbase_path options also accept aproc or alambda to evaluate, which is passed arequest object:

add_swagger_documentation \base_path:proc{ |request|request.host =~/^example/ ?'/api-example' :'/api'}

host:

Sets explicit thehost, default would be taken fromrequest.

add_swagger_documentation \host:'www.example.com'

base_path:

Base path of the API that's being exposed, default would be taken fromrequest.

add_swagger_documentation \base_path:nil

host andbase_path are also accepting aproc orlambda

mount_path:

The path where the API documentation is loaded, default is:/swagger_doc.

add_swagger_documentation \mount_path:'/swagger_doc'

add_base_path:

AddbasePath key to the documented path keys, default is:false.

add_swagger_documentation \add_base_path:true# only if base_path given

add_root:

Add root element to all the responses, default is:false.

add_swagger_documentation \add_root:true

add_version:

Addversion key to the documented path keys, default is:true,here the version is the API version, specified bygrape inpath

add_swagger_documentation \add_version:true

doc_version:

Specify the version of the documentation atinfo section, default is:'0.0.1'

add_swagger_documentation \doc_version:'0.0.1'

endpoint_auth_wrapper:

Specify the middleware to use for securing endpoints.

add_swagger_documentation \endpoint_auth_wrapper:WineBouncer::OAuth2

swagger_endpoint_guard:

Specify the method and auth scopes, used by the middleware for securing endpoints.

add_swagger_documentation \swagger_endpoint_guard:'oauth2 false'

token_owner:

Specify the token_owner method, provided by the middleware, which is typically named 'resource_owner'.

add_swagger_documentation \token_owner:'resource_owner'

security_definitions:

Specify theSecurity Definitions Object

NOTE:Swagger-UI is supporting only implicit flow yet

add_swagger_documentation \security_definitions:{api_key:{type:"apiKey",name:"api_key",in:"header"}}

security:

Specify theSecurity Object

add_swagger_documentation \security:[{api_key:[]}]

models:

A list of entities to document. Combine with thegrape-entity gem.

These would be added to the definitions section of the swagger file.

add_swagger_documentation \models:[TheApi::Entities::UseResponse,TheApi::Entities::ApiError]

tags:

A list of tags to document. By default tags are automatically generatedfor endpoints based on route names.

add_swagger_documentation \tags:[{name:'widgets',description:'A description of widgets'}]

hide_documentation_path: (default:true)

add_swagger_documentation \hide_documentation_path:true

Don't show the/swagger_doc path in the generated swagger documentation.

info:

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",}

A hash merged into theinfo key of the JSON documentation.

array_use_braces:

add_swagger_documentation \array_use_braces:true

This setting must betrue in order for params defined as anArray type to submit each element properly.

paramsdooptional:metadata,type:Array[String]end

witharray_use_braces: true:

metadata[]: { "name": "Asset ID", "value": "12345" }metadata[]: { "name": "Asset Tag", "value": "654321"}

witharray_use_braces: false:

metadata: {"name": "Asset ID", "value": "123456"}metadata: {"name": "Asset Tag", "value": "654321"}

api_documentation

Customize the Swagger API documentation route, typically contains adesc field. The default description is "Swagger compatible API description".

add_swagger_documentation \api_documentation:{desc:'Reticulated splines API swagger-compatible documentation.'}

specific_api_documentation

Customize the Swagger API specific documentation route, typically contains adesc field. The default description is "Swagger compatible API description for specific API".

add_swagger_documentation \specific_api_documentation:{desc:'Reticulated splines API swagger-compatible endpoint documentation.'}

consumes

Customize the Swagger API default globalconsumes field value.

add_swagger_documentation \consumes:['application/json','application/x-www-form-urlencoded']

produces

Customize the Swagger API default globalproduces field value.

add_swagger_documentation \produces:['text/plain']

Routes Configuration

Swagger Header Parameters

Swagger also supports the documentation of parameters passed in the header. Since grape'sparams[] doesn't return header parameters we can specify header parameters separately in a block after the description.

desc"Return super-secret information",{headers:{"XAuthToken"=>{description:"Valdates your identity",required:true},"XOptionalHeader"=>{description:"Not really needed",required:false}}}

Hiding an Endpoint

You can hide an endpoint by addinghidden: true in the description of the endpoint:

desc'Hide this endpoint',hidden:true

Or by addinghidden: true on the verb method of the endpoint, such asget,post andput:

get'/kittens',hidden:truedo

Or by using a route setting:

route_setting:swagger,{hidden:true}get'/kittens'do

Endpoints can be conditionally hidden by providing a callable object such as a lambda which evaluates to the desiredstate:

desc'Conditionally hide this endpoint',hidden:lambda{ENV['EXPERIMENTAL'] !='true'}

Overriding Auto-Generated Nicknames

You can specify a swagger nickname to use instead of the auto generated name by adding:nickname 'string' in the description of the endpoint.

desc'Get a full list of pets',nickname:'getAllPets'

Specify endpoint details

To specify further details for an endpoint, use thedetail option within a block passed todesc:

desc'Get all kittens!'dodetail'this will expose all the kittens'endget'/kittens'do

Overriding the route summary

To override the summary, addsummary: '[string]' after the description.

namespace'order'dodesc'This will be your summary',summary:'Now this is your summary!'get:order_iddo    ...endend

Overriding the tags

Tags are used for logical grouping of operations by resources or any other qualifier. To override thetags array, addtags: ['tag1', 'tag2'] after the description.

namespace'order'dodesc'This will be your summary',tags:['orders']get:order_iddo    ...endend

Deprecating routes

To deprecate a route adddeprecated: true after the description.

namespace'order'dodesc'This is a deprecated route',deprecated:trueget:order_iddo    ...endend

Overriding the name of the body parameter

By default, body parameters have a generated name based on the operation. Fordeeply nested resources, this name can get very long. To override the name ofbody parameter addbody_name: 'post_body' after the description.

namespace'order'dodesc'Create an order',body_name:'post_body'postdo    ...endend

Defining an endpoint as an array

You can define an endpoint as an array by addingis_array in the description:

desc'Get a full list of pets',is_array:true

Using an options hash

The Grape DSL supports either an options hash or a restricted block to pass settings. Passing thenickname,hidden andis_array options together with response codes is only possible when passing an options hash.Since the syntax differs you'll need to adjust it accordingly:

desc'Get all kittens!',{hidden:true,is_array:true,nickname:'getKittens',success:Entities::Kitten,# or successfailure:[[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

Overriding parameter type

You can override paramType, using the documentation hash. Seeparameter object for available types.

paramsdorequires:action,type:Symbol,values:[:PAUSE,:RESUME,:STOP],documentation:{param_type:'query'}endpost:actdo  ...end

Overriding data type of the parameter

You can override type, using the documentation hash.

paramsdorequires:input,type:String,documentation:{type:'integer'}endpost:actdo  ...end
{"in":"formData","name":"input","type":"integer","format":"int32","required":true}

Multiple types

By default when you set multiple types, the first type is selected as swagger type

paramsdorequires:action,types:[String,Integer]endpost:actdo  ...end
{"in":"formData","name":"action","type":"string","required":true}

Array of data type

Array types are also supported.

paramsdorequires:action_ids,type:Array[Integer]endpost:actdo  ...end
{"in":"formData","name":"action_ids","type":"array","items": {"type":"integer"  },"required":true}

Collection format of arrays

You can set the collection format of an array, using the documentation hash.

Collection format determines the format of the array if type array is used. Possible values are:

  • csv - comma separated values foo,bar.
  • ssv - space separated values foo bar.
  • tsv - tab separated values foo\tbar.
  • pipes - pipe separated values foo|bar.
  • multi - corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in "query" or "formData".
paramsdorequires:statuses,type:Array[String],documentation:{collectionFormat:'multi'}endpost:actdo  ...end
{"in":"formData","name":"statuses","type":"array","items": {"type":"string"  },"collectionFormat":"multi","required":true}

Hiding parameters

Exclude single optional parameter from the documentation

not_admins=lambda{ |token_owner=nil|token_owner.nil? || !token_owner.admin?}paramsdooptional:one,documentation:{hidden:true}optional:two,documentation:{hidden:->{ |t=nil|true}}optional:three,documentation:{hidden:not_admins}endpost:actdo  ...end

Setting a Swagger default value

Grape allows for an additional documentation hash to be passed to a parameter.

paramsdorequires:id,type:Integer,desc:'Coffee ID'requires:temperature,type:Integer,desc:'Temperature of the coffee in celcius',documentation:{default:72}end

Grape uses the optiondefault to set a default value for optional parameters. This is different in that Grape will set your parameter to the provided default if the parameter is omitted, whereas the example value above will only set the value in the UI itself. This will set the SwaggerdefaultValue to the provided value. Note that the example value will override the Grape default value.

paramsdorequires:id,type:Integer,desc:'Coffee ID'optional:temperature,type:Integer,desc:'Temperature of the coffee in celcius',default:72end

SettingadditionalProperties forobject-type parameters

Use theadditional_properties option in thedocumentation hash forobject-type parameters to setadditionalProperties.

Allow any additional properties

paramsdooptional:thing,type:Hash,documentation:{additional_properties:true}end

Allow any additional properties of a particular type

paramsdooptional:thing,type:Hash,documentation:{additional_properties:String}end

Allow any additional properties matching a defined schema

classEntity <Grape::Entityexpose:thisendparamsdooptional:thing,type:Hash,documentation:{additional_properties:Entity}end

Example parameter value

The example parameter will populate the Swagger UI with the example value, and can be used for optional or required parameters.

paramsdorequires:id,type:Integer,documentation:{example:123}optional:name,type:String,documentation:{example:'Buddy Guy'}end

Expose nested namespace as standalone route

Use thenested: false property in theswagger option to make nested namespaces appear as standalone resources.This option can help to structure and keep the swagger schema simple.

namespace'store/order',desc:'Order operations within a store',swagger:{nested:false}doget:order_iddo  ...endend

All routes that belong to this namespace (here: theGET /order_id) will then be assigned to thestore_order route instead of thestore resource route.

It is also possible to expose a namespace within another already exposed namespace:

namespace'store/order',desc:'Order operations within a store',swagger:{nested:false}doget:order_iddo  ...endnamespace'actions',desc:'Order actions',nested:falsedoget'evaluate'do      ...endendend

Here, theGET /order_id appears as operation of thestore_order resource and theGET /evaluate as operation of thestore_orders_actions route.

With a custom name

Auto generated names for the standalone version of complex nested resource do not have a nice look.You can set a custom name with thename property inside theswagger option, but only if the namespace gets exposed as standalone route.The name should not contain whitespaces or any other special characters due to further issues within swagger-ui.

namespace'store/order',desc:'Order operations within a store',swagger:{nested:false,name:'Store-orders'}doget:order_iddo  ...endend

Response documentation

You can also document the HTTP status codes with a description and a specified model, as ref in the schema to the definitions, that your API returns with one of the following syntax.

In the following cases, the schema ref would be taken from route.

desc'thing',failure:[{code:400,message:'Invalid parameter entry'}]get'/thing'do# ...end
desc'thing'doparamsEntities::Something.documentationfailure[{code:400,message:'Invalid parameter entry'}]endget'/thing'do# ...end
get'/thing',failure:[{code:400,message:'Invalid parameter entry'},{code:404,message:'Not authorized'},]do# ...end

By adding amodel key, e.g. this would be taken. Setting an empty string will act like an empty body.

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

If no status code is defineddefaults would be taken.

The result is then something like following:

"responses": {"200": {"description":"get Horses","schema": {"$ref":"#/definitions/Thing"    }  },"401": {"description":"HorsesOutError","schema": {"$ref":"#/definitions/ApiError"    }  }},

Changing default status codes

The default status codes, one could be found (->status codes) can be changed to your specific needs, to achieve it, you have to change it for grape itself and for the documentation.

desc'Get a list of stuff',success:{code:202,model:Entities::UseResponse,message:'a changed status code'}getdostatus202# your code comes hereend
"responses": {"202": {"description":"ok","schema": {"$ref":"#/definitions/UseResponse"    }  }},

Multiple status codes for response

Multiple values can be provided forsuccess andfailure attributes in the response.

desc'Attach a field to an entity through a PUT',success:[{code:201,model:Entities::UseResponse,message:'Successfully created'},{code:204,message:'Already exists'}],failure:[{code:400,message:'Bad request'},{code:404,message:'Not found'}]putdo# your code comes hereend
"responses": {"201": {"description":"Successfully created","schema": {"$ref":"#/definitions/UseResponse"    }  },"204": {"description":"Already exists"  },"400": {"description":"Bad request"  },"404": {"description":"Not found"  }},

File response

Settingsuccess toFile sets a defaultproduces ofapplication/octet-stream.

desc'Get a file',success:Filegetdo# your file responseend
"produces": ["application/octet-stream"],"responses": {"200": {"description":"Get a file","schema": {"type":"file"    }  }}

Default response

By setting thedefault option you can also define a default response that is the result returned for all unspecified status codes.The definition supports the same syntax assuccess orfailure.

In the following cases, the schema ref would be taken from route.

desc'thing',default:{message:'the default response'}get'/thing'do# ...end

The generated swagger section will be something like

"responses": {"default": {"description":"the default response"  }},

Just like withsuccess orfailure you can also provide amodel parameter.

desc'Get a list of stuff',default:{model:Entities::UseResponse,message:'the default response'}getdo# your code comes hereend

The generated swagger document will then correctly reference the model schema.

"responses": {"default": {"description":"the default response","schema": {"$ref":"#/definitions/UseResponse"    }  }},

Extensions

Swagger spec2.0 supports extensions on different levels, for the moment,the documentation on the root level object and theinfo,verb,path anddefinition levels are supported.

The documented key would be generated from thex +- + key of the submitted hash,for possibilities refer to theextensions spec.To get an overviewhow the extensions would be defined on grape level, see the following examples:

  • root object extension, add ax key to the root hash when callingadd_swagger_documentation:
add_swagger_documentation \x:{some:'stuff'},info:{}

this would generate:

{"x-some":"stuff","info":{  }}
  • info extension, add ax key to theinfo hash when callingadd_swagger_documentation:
add_swagger_documentation \info:{x:{some:'stuff'}}

this would generate:

"info":{"x-some":"stuff"}
  • verb extension, add ax key to thedesc hash:
desc'This returns something with extension on verb level',x:{some:'stuff'}

this would generate:

"/path":{"get":{"…":"","x-some":"stuff"  }}
  • operation extension, by setting via route settings::
route_setting:x_operation,{some:'stuff'}

this would generate:

"/path":{"get":{"…":"","x-some":"stuff"  }}
  • path extension, by setting via route settings:
route_setting:x_path,{some:'stuff'}

this would generate:

"/path":{"x-some":"stuff","get":{"…":"",  }}
  • definition extension, again by setting via route settings,here the status code must be provided, for which definition the extensions should be:
route_setting:x_def,{for:422,other:'stuff'}

this would generate:

"/definitions":{"ApiError":{"x-other":"stuff","…":"",  }}

or, for more definitions:

route_setting:x_def,[{for:422,other:'stuff'},{for:200,some:'stuff'}]
  • params extension, add ax key to thedocumentation hash :
requires:foo,type:String,documentation:{x:{some:'stuff'}}

this would generate:

{"in":"formData","name":"foo","type":"string","required":true,"x-some":"stuff"}

Response examples documentation

You can also add examples to your responses by using thedesc DSL with block syntax.

By specifying examples tosuccess andfailure.

desc'This returns examples'dosuccessmodel:Thing,examples:{'application/json'=>{description:'Names list',items:[{id:'123',name:'John'}]}}failure[[404,'NotFound',ApiError,{'application/json'=>{code:404,message:'Not found'}}]]endget'/thing'do  ...end

The result will look like following:

"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"        }      }    }  }

Failure information can be passed as an array of arrays or an array of hashes.

Response headers documentation

You can also add header information to your responses by using thedesc DSL with block syntax.

By specifying headers tosuccess andfailure.

desc'This returns headers'dosuccessmodel: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'}}]]endget'/thing'do  ...end

The result will look like following:

"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"        }      }    }  }

Failure information can be passed as an array of arrays or an array of hashes.

Adding root element to responses

You can specify a custom root element for a successful response:

route_setting:swagger,root:'cute_kitten'desc'Get a kitten'dohttp_codes[{code:200,model:Entities::Kitten}]endget'/kittens/:id'doend

The result will look like following:

"responses": {"200": {"description":"Get a kitten","schema": {"type":"object","properties": {"cute_kitten": {"$ref":"#/definitions/Kitten" } }      }    }  }

If you specifytrue, the value of the root element will be deduced based on the model name.E.g. in the following example the root element will be "kittens":

route_setting:swagger,root:truedesc'Get kittens'dois_arraytruehttp_codes[{code:200,model:Entities::Kitten}]endget'/kittens'doend

The result will look like following:

"responses": {"200": {"description":"Get kittens","schema": {"type":"object","properties": {"type":"array","items": {"kittens": {"$ref":"#/definitions/Kitten" } } }      }    }  }

Multiple present Response

You can specify a custom multiple response by using theas key:

desc'Multiple response',success:[{model:Entities::EnumValues,as::gender},{model:Entities::Something,as::somethings}]endget'/things'do  ...end

The result will look like following:

"responses": {"200": {"description":"Multiple response","schema":{"type":"object","properties":{"gender":{"$ref":"#/definitions/EnumValues"          },"somethings":{"$ref":"#/definitions/Something"          }        }      }    }  }

You can also specify if the response is an array, with theis_array key:

desc'Multiple response with array',success:[{model:Entities::EnumValues,as::gender},{model:Entities::Something,as::somethings,is_array:true,required:true}]endget'/things'do  ...end

The result will look like following:

"responses": {"200": {"description":"Multiple response with array","schema":{"type":"object","properties":{"gender":{"$ref":"#/definitions/EnumValues"          },"somethings":{"type":"array","items":{"$ref":"#/definitions/Something"            }          }        },"required": ["somethings"]      }    }  }

Using Grape Entities

Add thegrape-entity andgrape-swagger-entity gem to your Gemfile.

The following example exposes statuses. And exposes statuses documentation adding :type, :desc and :required.The documented class/definition name could be set via#entity_name.

moduleAPImoduleEntitiesclassStatus <Grape::Entityexpose: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]}endclassLink <Grape::Entityexpose:href,documentation:{type:'url'}expose:rel,documentation:{type:'string'}defself.entity_name'LinkedStatus'endendendclassStatuses <Grape::APIversion'v1'desc'Statuses index',entity:API::Entities::Statusget'/statuses'dostatuses=Status.alltype=current_user.admin? ?:full ::defaultpresentstatuses,with:API::Entities::Status,type:typeenddesc'Creates a new status',entity:API::Entities::Status,params:API::Entities::Status.documentationpost'/statuses'do        ...endendend

Relationships

You may safely omittype from relationships, as it can be inferred. However, if you need to specify or override it, use the full name of the class leaving out any modules namedEntities orEntity.

1xN

moduleAPImoduleEntitiesclassClient <Grape::Entityexpose:name,documentation:{type:'string',desc:'Name'}expose:addresses,using:Entities::Address,documentation:{type:'Entities::Address',desc:'Addresses.',param_type:'body',is_array:true}endclassAddress <Grape::Entityexpose:street,documentation:{type:'string',desc:'Street.'}endendclassClients <Grape::APIversion'v1'desc'Clients index',params:Entities::Client.documentation,success:Entities::Clientget'/clients'do      ...endendadd_swagger_documentationend

1x1

Note:is_array isfalse by default.

moduleAPImoduleEntitiesclassClient <Grape::Entityexpose:name,documentation:{type:'string',desc:'Name'}expose:address,using:Entities::Address,documentation:{type:'Entities::Address',desc:'Addresses.',param_type:'body',is_array:false}endclassAddress <Grape::Entityexpose:street,documentation:{type:'string',desc:'Street'}endendclassClients <Grape::APIversion'v1'desc'Clients index',params:Entities::Client.documentation,success:Entities::Clientget'/clients'do      ...endendadd_swagger_documentationend

Inheritance with allOf and discriminator

moduleEntitiesclassPet <Grape::Entityexpose:type,documentation:{type:'string',is_discriminator:true,required:true}expose:name,documentation:{type:'string',required:true}endclassCat <Petexpose:huntingSkill,documentation:{type:'string',description:'The measured skill for hunting',default:'lazy',values:%w[cluelesslazyadventurousaggressive]}endend

Should generate this definitions:

{"definitions": {"Pet": {"type":"object","discriminator":"petType","properties": {"name": {"type":"string"        },"petType": {"type":"string"        }      },"required": ["name","petType"      ]    },"Cat": {"description":"A representation of a cat","allOf": [        {"$ref":"#/definitions/Pet"        },        {"type":"object","properties": {"huntingSkill": {"type":"string","description":"The measured skill for hunting","default":"lazy","enum": ["clueless","lazy","adventurous","aggressive"              ]            },"petType": {"type":"string","enum": ["Cat"]            }          },"required": ["huntingSkill","petType"          ]        }      ]    }  }}

Securing the Swagger UI

The Swagger UI on Grape could be secured from unauthorized access using any middleware, which provides certain methods:

  • some guard method, which could receive as argument a string or an array of authorization scopes;
  • abefore method to be run in the Grape controller for authorization purpose;
  • a set of methods which will process the access token received in the HTTP request headers (usually in the'HTTP_AUTHORIZATION' header) and try to return the owner of the token.

Below are some examples of securing the Swagger UI on Grape installed along with Ruby on Rails:

  • The WineBouncer and Doorkeeper gems are used in the examples;
  • 'rails' and 'wine_bouncer' gems should be required prior to 'grape-swagger' in boot.rb;
  • This works with a fresh PR to WineBouncer which is yet unmerged -WineBouncer PR.

This is how to configure the grape_swagger documentation:

add_swagger_documentationbase_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 UIswagger_endpoint_guard:'oauth2 false',# this is the guard method and scopetoken_owner:'resource_owner'# This is the method returning the owner of the token

The guard method should inject the Security Requirement Object into the endpoint's route settings (see Grape::DSL::Settings.route_setting method).

The 'oauth2 false' added to swagger_documentation is making the main Swagger endpoint protected with OAuth, i.e. theaccess_token is being retrieving from the HTTP request, but the 'false' scope is for skipping authorization andshowing the UI for everyone. If the scope would be set to something else, like 'oauth2 admin', for example, than the UIwouldn't be displayed at all to unauthorized users.

Further on, the guard could be used, where necessary, for endpoint access protection. Put it prior to the endpoint's method:

resource:usersdooauth2'read, write'getdorender_usersendoauth2'admin'postdoUser.create!...endend

And, finally, if you want to not only restrict the access, but to completely hide the endpoint from unauthorizedusers, you could pass a lambda to the :hidden key of a endpoint's description:

not_admins=lambda{ |token_owner=nil|token_owner.nil? || !token_owner.admin?}resource:usersdodesc'Create user',hidden:not_adminsoauth2'admin'postdoUser.create!...endend

The lambda is checking whether the user is authenticated (if not, the token_owner is nil by default), and has the adminrole - only admins can see this endpoint.

Example

Go into example directory and run it:$ bundle exec rackupgo to:http://localhost:9292/swagger_doc to get it

For request examples load thepostman file

Grouping the API list using Namespace

Use namespace for grouping APIs

grape-swagger-v2-new-corrected

Example Code

classNamespaceApi <Grape::APInamespace:hudsondodesc'Document root'get'/'doenddesc'This gets something.',detail:'_test_'get'/simple'do{bla:'something'}endendnamespace:downloaddodesc'download files',success:File,produces:['text/csv']get':id'do# file responseendendend

Rake Tasks

Add these lines to your Rakefile, and initialize the Task class with your Api class.

require'grape-swagger/rake/oapi_tasks'GrapeSwagger::Rake::OapiTasks.new(::Api::Base)

You may initialize with the class name as a string if the class is not yet loaded at the time Rakefile is parsed:

require'grape-swagger/rake/oapi_tasks'GrapeSwagger::Rake::OapiTasks.new('::Api::Base')

OpenApi/Swagger Documentation

rake oapi:fetchparams:- store={ true | file_name.json } – save as JSON (optional)- resource=resource_name     – get only for this one (optional)

For multiversion API it creates several files with following naming: file_name_API_VERSION.json

OpenApi/Swagger Validation

requires:npm andswagger-cli to be installed

rake oapi:validateparams:- resource=resource_name – get only for this one (optional)

Contributing to grape-swagger

SeeCONTRIBUTING.

Copyright and License

Copyright (c) 2012-2016 Tim Vandecasteele, ruby-grape and contributors. SeeLICENSE.txt for details.

About

Add OAPI/swagger v2.0 compliant documentation to your grape API

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors177

Languages


[8]ページ先頭

©2009-2025 Movatter.jp