Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
Z

zero-rails_openapi

> 后端框架
Open source

Concise DSL for generating OpenAPI Specification 3 (OAS3) JSON documentation for Ruby application.

170 stars0 likes2 views
WebsiteGitHub

About

Concise DSL for generating OpenAPI Specification 3 (OAS3) JSON documentation for Ruby application.

ZRO: OpenApi 3 JSON-Doc Generator for Rails

Concise DSL for generating OpenAPI Specification 3 (OAS3, formerly Swagger3) JSON documentation for Rails application.

NOTE: use [action_spec](https://github.com/action-spec/action_spec) instead

NOTE: use [action_spec](https://github.com/action-spec/action_spec) instead

ruby
class Api::ExamplesController  [ { id: Integer, name: String }, dft: { id: 1, name: 'pet' } ]
  query! :UidQuery  => [ :uid, String, desc: 'uid' ]
  response :BadRqResp => [ 'bad request', :json ]
end

# to use component
api :action do
  query :doge, :DogSchema # to use a Schema component
  param_ref :UidQuery     # to use a Parameter component
  response_ref :BadRqResp # to use a Response component
end

Each RefObj is associated with components through component key.

We suggest that component keys should be camelized, and must be Symbol.

(4) api [required]

For defining API (or we could say controller action).

ruby
# ** Method Signature
api action_name, summary = '', id: nil, tag: nil, http: nil, dry: Config.default_run_dry, &block
# ** Usage
api :index, '(SUMMARY) this api blah blah ...', # block ...

Parameters explanation:

  1. action_name: must be the same as controller action name
  2. id: operationId
  3. http: HTTP method (like: 'GET' or 'GET|POST')

(5) api_dry [optional]

This method is for DRYing. The blocks passed to api_dry will be executed to the specified APIs which are having the actions or tags in the class.

ruby
# ** Method Signature
api_dry action_or_tags = :all, &block
# ** Usage
api_dry :all, 'common response' # block ...
api_dry :index # block ...
api_dry :TagA # block ...

api_dry [:index, :show] do
  query #...
end

And then you should call dry method (detailed info) for executing the declared dry blocks:

ruby
api :index do
  dry
end

DSLs written inside api and api_dry's block

source code

These following methods in the block describe the specified API action: description, valid?, parameters, request body, responses, securities and servers.

(Here corresponds to OAS Operation Object)

(1) this_api_is_invalid!, and its aliases:

this_api_is_expired!
this_api_is_unused!
this_api_is_under_repair!
ruby
# ** Method Signature
this_api_is_invalid!(*)
# ** Usage
this_api_is_invalid! 'cause old version'

After that, deprecated field of this API will be set to true.

(2) desc: description for the current API

ruby
# ** Method Signature
desc string
# ** Usage
desc "current API's description"

(3) param family methods (OAS - Parameter Object)

To define parameter for APIs.

param                              # 1. normal usage
param_ref                          # 2. links sepcified RefObjs (by component keys) to current parameters.
header,  path,  query,  cookie     # 3. passes specified parameter location (like header) to `param`
header!, path!, query!, cookie!    # 4. bang method of above methods
in_* by: { parameter_definations } # 5. batch definition, such as `in_path`, `in_query`
examples                           # 6. examples of parameters

The bang method and param_name (which's name is end of a exclamation point !) means this param is required. Without ! means optional. THE SAME BELOW.

…

[A] OpenAPI 3.0 distinguishes between the following parameter types based on the parameter location: header, path, query, cookie. more info

[B] If param_type is path, for example: if the API path is /good/:id, you have to declare a path parameter named id

(4) request_body family methods (OAS - Request Body Object)

OpenAPI 3.0 uses the requestBody keyword to distinguish the payload from parameters.

Notice: Each API has only ONE request body object. Each request body object can has multiple media types. It means: call request_body multiple times, (schemas) will be deeply merged (let's call it fusion) into a request body object.

request_body  # 1. normal usage
body_ref      # 2. it links sepcified RefObjs (by component keys) to the body.
body, body!   # 3. alias of request_body
form, form!   # 4. to define a multipart/form-data request_body
json, json!   # 5. to define a application/json request_body
data          # 5. to define [a] property in the form-data request_body

Bang methods(!) means the specified media-type body is required.

…

How fusion works:

  1. Difference media types will be merged into requestBody["content"]
ruby
form data: { }
body :json, data: { }
# will generate: "content": { "multipart/form-data": { }, "application/json": { } }
  1. The same media-types will be deeply merged together, including their required array:
    (So that you can call form multiple times)
ruby
data :param_a!, String
data :param_b,  Integer
# or same as:
form data: { :param_a! => String }
form data: { :param_b  => Integer }
# will generate: { "param_a": { "type": "string" }, "param_b": { "type": "integer" } } (call it X)
# therefore:
#   "content": { "multipart/form-data":
#     { "schema": { "type": "object", "properties": { X }, "required": [ "param_a" ] }
#   }

(5) response family methods (OAS - Response Object)

To define the response for APIs.

response      # 1. aliases: `resp` and `error`
response_ref  # 2. it links sepcified RefObjs (by component keys) to the response.
ruby
# ** Method Signature
response code, desc, media_type = nil, headers: { }, data: { }, **options
# ** Usage
resp 200, 'success', :json, data: { name: 'test' }
response 200, 'query result', :pdf, data: File
response :success, 'succ', :json, headers: { 'X-Request-Start': String }, data: { }

# ** Method Signature
response_ref code_and_compkey_hash
# ** Usage
response_ref 700 => :AResp, 800 => :BResp

(6) Callback (OAS - Callback Object)

About Callbacks

In OpenAPI 3 specs, you can define callbacks – asynchronous, out-of-band requests that your service will send to some other service in response to certain events. This helps you improve the workflow your API offers to clients.
A typical example of a callback is a subscription functionality ... you can define the format of the “subscription” operation as well as the format of callback messages and expected responses to these messages.
This description will simplify communication between different servers and will help you standardize use of webhooks in your API.
Complete YAML Example

The structure of Callback Object:

callbacks:
  Event1:
    path1:
      ...
    path2:
     ...
  Event2:
    ...

callback method is for defining callbacks.

ruby
# ** Method Signature
callback event_name, http_method, callback_url, &block
# ** Usage
callback :myEvent, :post, 'localhost:3000/api/goods' do
  query :name, String
  data :token, String
  response 200, 'success', :json, data: { name: String, description: String }
end

Use runtime expressions in callback_url:

ruby
callback :myEvent, :post, '{body callback_addr}/api/goods/{query id}'
# the final URL will be: {$request.body#/callback_addr}/api/goods/{$request.query.id}
# Note: Other expressions outside "$request" are not supported yet

(7) Authentication and Authorization

First of all, please make sure that you have read one of the following documents: OpenApi Auth or securitySchemeObject

Define Security Scheme

Use these DSL in your initializer config or components block:

security_scheme # alias `auth_scheme`
base_auth       # will call `security_scheme`
bearer_auth     # will call `security_scheme`
api_key         # will call `security_scheme`

It's very simple to use (if you understand the above document)

ruby
# ** Method Signature
security_scheme scheme_name, other_info
# ** Usage
security_scheme :BasicAuth, { type: 'http', scheme: 'basic', desc: 'basic auth' }

# ** Method Signature
base_auth scheme_name, other_info = { }
bearer_auth scheme_name, format = 'JWT', other_info = { }
api_key scheme_name, field:, in:, **other_info
# ** Usage
base_auth :BasicAuth, desc: 'basic auth' # the same effect as above
bearer_auth :Token
api_key :ApiKeyAuth, field: 'X-API-Key', in: 'header', desc: 'pass api key to header'
Apply Security
# Use in initializer (Global effectiveness)
global_security_require # alias: global_security & global_auth

# Use in `api`'s block (Only valid for the current controller)
security_require # alias security & auth_with
ruby
# ** Method Signature
security_require scheme_name, scopes: [ ]
# ** Usage
global_auth :Token
auth_with   :OAuth, scopes: %w[ read_example admin ]

(8) Overriding Global Servers by server

ruby
# ** Method Signature
server url, desc: ''
# ** Usage
server 'http://localhost:3000', desc: 'local'

(9) dry

You have to call dry method inside api block, or pass dry: true as parameter of api, for executing the dry blocks you declared before. Otherwise nothing will happen.

ruby
# ** Method Signature
dry only: nil, skip: nil, none: false

# ** Usage
# In general, just:
dry
# To skip some params declared in dry blocks:
dry skip: [:id, :name]
# `only` is used to specify which parameters will be taken from dry blocks
dry only: [:id]

DSLs written inside components's block

code source (Here corresponds to OAS Components Object)

Inside components's block, you can use the same DSLs as DSLs written inside api and api_dry's block.
But notice there are two differences:

(1) Each method needs to pass one more parameter component_key (as the first parameter), it will be used as the reference name for the component.

ruby
query! :UidQuery, :uid, String, desc: 'it is a component'
#         ↑         ↑
# component_key  param_name

# You can also use "arrow writing", it may be easier to understand
query! :UidQuery => [:uid, String, desc: '']

(2) You can use schema to define a Schema Component.

…

To enable load schema from database, you must set model base correctly.

Schema and Type

schema and type -- contain each other

(Schema) Type

Support all [data types](htt

Issues· 9 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyapi-documentation-tooloasopenapi-specificationrails

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架