grape-swagger

grape-swagger

Grape API的自动Swagger文档生成工具

grape-swagger是一个专为Grape API设计的Ruby gem,能够自动生成符合Swagger规范的API文档。它可以轻松整合到现有Grape项目中,输出可在Swagger UI中浏览的文档。该工具具有丰富的配置选项,包括自定义主机、基础路径和安全定义等。grape-swagger还支持与grape-entity和representable等流行的模型解析器集成,为开发者提供了一个高效的API文档管理解决方案,有效提升了API的可发现性和可用性。

grape-swaggerAPI文档SwaggerRubyGrapeGithub开源项目

Gem Version Build Status Coverage Status Code Climate

Table of Contents

What is grape-swagger? <a name="what"></a>

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

Demo Screenshot

This screenshot is based on the Hussars sample app.

Related Projects <a name="related"></a>

Compatibility <a name="version"></a>

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

Swagger-Spec <a name="swagger-spec"></a>

Grape-swagger generates documentation per Swagger / OpenAPI Spec 2.0.

<!-- validating it with: http://bigstickcarpet.com/swagger-parser/www/index.html -->

Installation <a name="install"></a>

Add to your Gemfile:

gem 'grape-swagger'

Upgrade

Please see UPGRADING when upgrading from a previous version.

Usage <a name="usage"></a>

Mount all your different APIs (with Grape::API superclass) on a root node. In the root class definition, include add_swagger_documentation, this sets up the system and registers the documentation on '/swagger_doc'. See example/config.ru for a simple demo.

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

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

Model Parsers <a name="model_parsers"></a>

Since 0.21.0, Grape::Entity is not a part of grape-swagger, you need to add grape-swagger-entity manually to your Gemfile. Also added support for representable via grape-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., via require 'grape-swagger/entity' or require 'grape-swagger/representable'.

Custom Model Parsers

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

module GrapeSwagger module Roar class Parser attr_reader :model attr_reader :endpoint def initialize(model, endpoint) @model = model @endpoint = endpoint end def call # Parse your model and return hash with model schema for swagger end end end end

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 uses Representable::Decorator as a superclass, this allows to avoid a problem when Roar objects are processed by GrapeSwagger::Representable::Parser instead of GrapeSwagger::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. Use rack-cors to enable CORS.

require 'rack/cors' use Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: [ :get, :post, :put, :delete, :options ] end end

Alternatively you can set CORS headers in a Grape before block.

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

Configure <a name="configure"></a>

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

The host and base_path options also accept a proc or a lambda to evaluate, which is passed a request object:

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

host: <a name="host"></a>

Sets explicit the host, default would be taken from request.

add_swagger_documentation \ host: 'www.example.com'

base_path: <a name="base_path"></a>

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

add_swagger_documentation \ base_path: nil

host and base_path are also accepting a proc or lambda

mount_path: <a name="mount_path"></a>

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

add_swagger_documentation \ mount_path: '/swagger_doc'

add_base_path: <a name="add_base_path"></a>

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

add_swagger_documentation \ add_base_path: true # only if base_path given

add_root: <a name="add_root"></a>

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

add_swagger_documentation \ add_root: true

add_version: <a name="add_version"></a>

Add version key to the documented path keys, default is: true, here the version is the API version, specified by grape in path

add_swagger_documentation \ add_version: true

doc_version: <a name="doc_version"></a>

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

add_swagger_documentation \ doc_version: '0.0.1'

endpoint_auth_wrapper: <a name="endpoint_auth_wrapper"></a>

Specify the middleware to use for securing endpoints.

add_swagger_documentation \ endpoint_auth_wrapper: WineBouncer::OAuth2

swagger_endpoint_guard: <a name="swagger_endpoint_guard"></a>

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

add_swagger_documentation \ swagger_endpoint_guard: 'oauth2 false'

token_owner: <a name="token_owner"></a>

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

add_swagger_documentation \ token_owner: 'resource_owner'

security_definitions: <a name="security_definitions"></a>

Specify the Security 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: <a name="security"></a>

Specify the Security Object

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

models: <a name="models"></a>

A list of entities to document. Combine with the grape-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 name="tags"></a>

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

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

hide_documentation_path: (default: true) <a name="hide_documentation_path"></a>

add_swagger_documentation \ hide_documentation_path: true

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

info: <a name="info"></a>

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 the info key of the JSON documentation.

array_use_braces: <a name="array_use_braces"></a>

add_swagger_documentation \ array_use_braces: true

This setting must be true in order for params defined as an Array type to submit each element properly.

params do optional :metadata, type: Array[String] end

with array_use_braces: true:

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

with array_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 a desc 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 a desc 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 global consumes field value.

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

produces

Customize the Swagger API default global produces field value.

add_swagger_documentation \ produces: ['text/plain']

Routes Configuration <a name="routes"></a>

编辑推荐精选

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

下拉加载更多