grape_openapi3 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 567bc33ad5a25000b165090cc8defe1d5e819fb6c8a5df0cccbab2dddb27cca4
4
- data.tar.gz: 74bebc4d7030935208f01fb429362b26041522f7616d3949e02a9d5b8a104765
3
+ metadata.gz: 4d46572297963e73804e00ac25c1c26ca92830c6f54efc95e472ac07d8a8c88d
4
+ data.tar.gz: 116e9f799e622500af92fc255fd766a5a39e48cf02bff7fdc474bd49a627204e
5
5
  SHA512:
6
- metadata.gz: 1c640016dab4cb6e03d32bc9af02c3d3a22ea060ed94a3cbe6bdabbc83e423a6a0df01211460567ea155091b23ae031093ef979f1f878d770df5f560470e6ae0
7
- data.tar.gz: 67ebcdac076ec212d794ca4aae5f7ecf4ddcdc1640557e9c63652dfe44af345407ae5c7558c4edf61e60d6cb5f49151cbdfe6ef0fdb31473e949f8332b268fd3
6
+ metadata.gz: dbbd91854d9700ad064805085461d47b5995ca5b4e4fa9febe9cdd54be94ec6394d2549f4f6f59b82995dc902235188a66624e3e0ad47338d5d86172b355e86d
7
+ data.tar.gz: 46a5a6f6869dbc7c1d8d00c434c95f9ce72b72c44ad39d7fd32a311feee859250ee5a8a11dfa28f085da8baf323f1f5b86a8d7f93b0089d39d9a226e757aad41
data/CHANGELOG.md ADDED
@@ -0,0 +1,140 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.7] - 2026-12-03
11
+
12
+ ### Added
13
+ - **Strict mode**: `generate(..., strict: :warn | true)` reports every documentation
14
+ gap — untyped exposures and params, unknown types, unresolvable `using:` entities,
15
+ `200` responses without a schema — as warnings or a `GrapeOpenapi3::StrictModeError`.
16
+ - Entity block exposures (`expose :stats do … end`) become inline object schemas
17
+ with their own `required` list.
18
+ - `merge: true` exposures (entity or block) are flattened into the parent schema.
19
+ - Entity documentation keywords: `min_length`, `max_length`, `pattern` (Ruby
20
+ `Regexp` converted to ECMA), `multiple_of`, `min_items`, `max_items`,
21
+ `unique_items`, `read_only`, `write_only`, `deprecated` (snake_case or camelCase).
22
+ - Param validations become schema keywords: `regexp:` → `pattern`, `length:` →
23
+ `minLength`/`maxLength` (strings) or `minItems`/`maxItems` (arrays),
24
+ `allow_blank: false` → `minLength: 1`; plus the entity keywords inside a param's
25
+ `documentation:` hash.
26
+ - `values:` Ranges become `minimum`/`maximum` (endless and beginless ranges too);
27
+ zero-arity procs are evaluated into an `enum`.
28
+ - Header parameters from `desc headers: { … }`.
29
+ - Several success responses: `success: [{ code: 200, model: … }, { code: 202, … }]`.
30
+ - Explicit operationIds with `desc …, nickname:` (or `operation_id:`).
31
+ - Variant types (`types: [Integer, String]`) → `oneOf`; `JSON` → object or array
32
+ of objects; `Array[JSON]` → array of objects.
33
+ - Lowercase OpenAPI type names (`"integer"`, `"number"`, …) and `Symbol` are
34
+ recognised instead of falling back to `string`.
35
+
36
+ ### Changed
37
+ - A nullable `$ref` is now emitted as `anyOf: [$ref, null-only schema]` instead of
38
+ `allOf: [$ref] + nullable: true`, which strict OpenAPI 3.0.3 validators reject
39
+ for `null`.
40
+ - operationIds are unique across the document: when a `PATCH` shares a path with a
41
+ `PUT`, the `PUT` keeps `update…` and the `PATCH` becomes `patch…` (then a numeric
42
+ suffix for any remaining clash).
43
+ - A `DELETE` without a success entity documents its `204` as "No Content"
44
+ (was "Success").
45
+ - The install generator's rake task defaults `OPENAPI_SERVER_URL` to
46
+ `http://localhost:3000`, reports gaps with `strict: :warn`, and explains that the
47
+ server URL must not repeat the Grape prefix already in the paths.
48
+
49
+ ### Fixed
50
+ - An endless or beginless `values:` Range (`(0..)`) raised `RangeError` and
51
+ aborted generation; a bounded one was exploded into a huge `enum`.
52
+ - A validator proc in `values:` leaked into `enum` as `"#<Proc…>"`.
53
+ - `values:` on an array param was applied to the array instead of its items.
54
+ - `BigDecimal` / `Rational` bounds and enum values were serialized as JSON strings
55
+ (`"minimum": "0.0"`), making the keyword invalid.
56
+ - Failure responses without a message had an empty (invalid) description; they now
57
+ use the HTTP reason phrase ("Conflict", "Bad Request", …).
58
+ - `success:` given as an Array was ignored.
59
+ - Conditional exposures (`if:`/`unless:`) were marked `required`.
60
+ - An unresolvable `using:` entity produced a broken `$ref`; it is now a plain object.
61
+
62
+ ### Example apps
63
+ - `example/` is now a catalog of every supported feature, generated with
64
+ `strict: true`.
65
+ - `example/rails_app/` adds `PATCH`, categories endpoints, param constraints, a
66
+ documented header, nullable/computed/block/conditional exposures, and
67
+ **contract tests** (`bundle exec rspec`) that validate every real response
68
+ against the generated document. Its rake task no longer doubles `/api/v1` in
69
+ the server URL.
70
+
71
+ ### Development
72
+ - Every generated document in the suite is validated against the official
73
+ OpenAPI 3.0 meta-schema (plus unique operationIds, resolvable `$ref`s, sane
74
+ responses); `example/openapi.json` is snapshot-tested.
75
+ - CI runs the example Rails app's contract tests and checks its static
76
+ `public/openapi.json` is up to date.
77
+
78
+ ## [0.1.6] - 2026-06-20
79
+
80
+ ### Added
81
+ - Typed error responses: `failure` entries can now carry a schema via `model:`
82
+ (a `Grape::Entity`, rendered as a `$ref`) or an inline `schema:`, so an
83
+ OpenAPI → TypeScript/Zod codegen can type error payloads, not just the
84
+ success body.
85
+ - Complete, runnable Rails 8 + Grape example app under `example/rails_app/`,
86
+ with a live-generated OpenAPI document and Swagger UI.
87
+
88
+ ## [0.1.5] - 2026-06-20
89
+
90
+ ### Changed
91
+ - Maintenance release rolling up the 0.1.4 generation improvements.
92
+
93
+ ## [0.1.4] - 2026-06-20
94
+
95
+ ### Added
96
+ - Collision-free schema names: the entity graph reachable from the routes is
97
+ pre-scanned and each entity gets a deterministic, collision-free schema name.
98
+ When two entities share a short name (e.g. `Mentors::MenteeResponse` vs
99
+ `Kids::MenteeResponse`), the shortest disambiguating namespace suffix is used
100
+ instead of one silently overwriting the other. Naming is stable regardless of
101
+ registration order.
102
+ - Nested params: flattened Grape bracket keys (`address[street]`, `tags[label]`)
103
+ are reassembled into nested object and array-of-object request-body schemas at
104
+ arbitrary depth.
105
+ - Entity value keywords: entity properties support `enum` (via `:values`/`:enum`),
106
+ `format`, `example`, `minimum`, `maximum` and `default`. Keywords land on the
107
+ scalar schema (or the array items for arrays of scalars).
108
+
109
+ ## [0.1.3] - 2026-06-15
110
+
111
+ ### Fixed
112
+ - Republish of 0.1.2.
113
+
114
+ ## [0.1.2] - 2026-06-15
115
+
116
+ ### Fixed
117
+ - Path parameters always take precedence over other param sources.
118
+ - `nullable` is emitted on optional params.
119
+
120
+ ## [0.1.1] - 2026-06-15
121
+
122
+ ### Changed
123
+ - Packaging and metadata fixes.
124
+
125
+ ## [0.1.0] - 2026-06-14
126
+
127
+ ### Added
128
+ - Initial release: native OpenAPI 3.0 document generation from Grape routes,
129
+ `params do` blocks, `desc` options and `Grape::Entity` response classes.
130
+ No grape-swagger and no Swagger 2.0 conversion step.
131
+
132
+ [Unreleased]: https://github.com/rodrigonbarreto/grape_openapi3/compare/v0.1.7...HEAD
133
+ [0.1.7]: https://github.com/rodrigonbarreto/grape_openapi3/compare/v0.1.6...v0.1.7
134
+ [0.1.6]: https://github.com/rodrigonbarreto/grape_openapi3/compare/v0.1.5...v0.1.6
135
+ [0.1.5]: https://github.com/rodrigonbarreto/grape_openapi3/compare/v0.1.3...v0.1.5
136
+ [0.1.4]: https://github.com/rodrigonbarreto/grape_openapi3/compare/v0.1.3...v0.1.5
137
+ [0.1.3]: https://github.com/rodrigonbarreto/grape_openapi3/compare/v0.1.2...v0.1.3
138
+ [0.1.2]: https://github.com/rodrigonbarreto/grape_openapi3/releases/tag/v0.1.2
139
+ [0.1.1]: https://github.com/rodrigonbarreto/grape_openapi3/releases/tag/v0.1.0
140
+ [0.1.0]: https://github.com/rodrigonbarreto/grape_openapi3/releases/tag/v0.1.0
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rodrigo Barreto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # grape_openapi3
2
2
 
3
+ [![Gem Version](https://badge.fury.io/rb/grape_openapi3.svg)](https://rubygems.org/gems/grape_openapi3)
4
+ [![Downloads](https://img.shields.io/gem/dt/grape_openapi3.svg)](https://rubygems.org/gems/grape_openapi3)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
+
3
7
  Generate **OpenAPI 3.0** documentation directly from your [Grape](https://github.com/ruby-grape/grape) API — no conversion, no middleman, no grape-swagger required.
4
8
 
5
9
  The gem reads your routes, `params do` blocks, `desc` options, and `Grape::Entity` classes and produces a valid `openapi.json` in one call.
@@ -105,8 +109,19 @@ success: { code: 200, message: "Done." }
105
109
 
106
110
  # Full form: code + entity + message
107
111
  success: { code: 201, model: Entities::ProductEntity, message: "Product created." }
112
+
113
+ # Array body: route-level is_array (or is_array: true inside the hash)
114
+ desc "List products", success: Entities::ProductEntity, is_array: true
115
+
116
+ # Several success responses, each with its own body
117
+ success: [
118
+ { code: 200, model: Entities::ProductEntity, is_array: true, message: "Imported synchronously" },
119
+ { code: 202, model: Entities::ImportJobEntity, message: "Import queued" },
120
+ ]
108
121
  ```
109
122
 
123
+ A `DELETE` without a success entity is documented as `204 No Content`.
124
+
110
125
  ### Failure options (typed error responses)
111
126
 
112
127
  Error responses can carry a schema too — point them at a `Grape::Entity` with
@@ -119,6 +134,7 @@ failure: [
119
134
  { code: 404, message: "Not found", model: Entities::ErrorEntity }, # $ref to a schema
120
135
  { code: 422, message: "Validation", model: Entities::ValidationErrorEntity },
121
136
  { code: 409, message: "Conflict", schema: { type: "object", properties: { code: { type: "string" } } } },
137
+ [429], # no message → "Too Many Requests"
122
138
  ]
123
139
  ```
124
140
 
@@ -139,6 +155,39 @@ end
139
155
  ```
140
156
 
141
157
  Both styles (`desc params:` hash and `params do` block) are supported and can be mixed.
158
+ Prefer one `params do` block per route: declaring the same param in both places
159
+ lets the two drift apart.
160
+
161
+ ### Param validations become schema keywords
162
+
163
+ Grape validations are translated, so the doc tells clients exactly what Grape accepts:
164
+
165
+ | Grape | OpenAPI |
166
+ |---|---|
167
+ | `values: %w[a b]` / `values: -> { %w[a b] }` | `enum` (a zero-arity proc is evaluated at generation time) |
168
+ | `values: 1..100` / `(1..)` / `(..30)` | `minimum` / `maximum` (never an exploded enum) |
169
+ | `values: ->(v) { … }` (validator proc) | omitted — it can't be expressed as a schema |
170
+ | `regexp: /\A[a-z]+\z/` | `pattern: "^[a-z]+$"` (Ruby anchors converted to ECMA) |
171
+ | `length: { min:, max: }` / `{ is: }` | `minLength`/`maxLength` on strings, `minItems`/`maxItems` on arrays |
172
+ | `allow_blank: false` | `minLength: 1` |
173
+ | `type: Array[String], values: […]` / `regexp:` | constraint applied to each **item** |
174
+ | `types: [Integer, String]` | `oneOf` |
175
+ | `type: JSON` / `Array[JSON]` | object-or-array-of-objects / array of objects |
176
+ | `documentation: { min_length:, deprecated:, … }` | same keywords as entities (below) |
177
+
178
+ > For `type: BigDecimal`, Grape requires range bounds of the same type:
179
+ > `values: (BigDecimal("0")..)`.
180
+
181
+ ### Header parameters
182
+
183
+ ```ruby
184
+ desc "List products", headers: {
185
+ "X-Tenant-Id" => { description: "Tenant the request acts on", required: true },
186
+ "X-Request-Id" => { description: "Optional trace id" },
187
+ }
188
+ ```
189
+
190
+ Each header becomes an `in: header` parameter.
142
191
 
143
192
  ---
144
193
 
@@ -166,6 +215,11 @@ class OrderEntity < Grape::Entity
166
215
  end
167
216
  ```
168
217
 
218
+ A nullable `$ref` is emitted as `anyOf: [{ $ref }, { type: object, nullable: true, enum: [null] }]`.
219
+ In OpenAPI 3.0.3 `nullable` only widens a `type` declared in the same schema, so
220
+ the common `allOf: [$ref] + nullable: true` form actually **rejects** `null` in
221
+ strict validators (`json_schemer`, `committee`, …).
222
+
169
223
  Array responses via `is_array: true`:
170
224
 
171
225
  ```ruby
@@ -176,6 +230,40 @@ class ProductListEntity < Grape::Entity
176
230
  end
177
231
  ```
178
232
 
233
+ ### Block, merged and conditional exposures
234
+
235
+ ```ruby
236
+ class ArticleEntity < BaseEntity # inherited exposures are included
237
+ # Block exposure → inline object with its own `required` list
238
+ expose :stats, documentation: { desc: "Engagement", required: true } do
239
+ expose :views, documentation: { type: Integer, required: true }
240
+ expose :rating, documentation: { type: Float }
241
+ end
242
+
243
+ # merge: true → AuditEntity's fields land directly on ArticleEntity
244
+ expose :audit, using: AuditEntity, merge: true
245
+
246
+ # Conditional (if:/unless:) → documented, but never `required` (it may be absent)
247
+ expose :internal_notes, if: ->(_, opts) { opts[:admin] },
248
+ documentation: { type: String, required: true }
249
+ end
250
+ ```
251
+
252
+ ### Entity documentation keywords
253
+
254
+ | `documentation:` key | OpenAPI | Lands on |
255
+ |---|---|---|
256
+ | `type`, `desc`, `required`, `nullable` | `type`, `description`, `required`, `nullable` | property |
257
+ | `values:` / `enum:` (list, Range, lazy proc) | `enum` / `minimum` + `maximum` | value* |
258
+ | `format`, `minimum`, `maximum` | same | value* |
259
+ | `min_length`, `max_length`, `pattern` (Regexp or String), `multiple_of` | `minLength`, `maxLength`, `pattern`, `multipleOf` | value* |
260
+ | `min_items`, `max_items`, `unique_items` | `minItems`, `maxItems`, `uniqueItems` | array |
261
+ | `read_only`, `write_only`, `deprecated` | `readOnly`, `writeOnly`, `deprecated` | property |
262
+ | `default`, `example` | same | property |
263
+
264
+ \* the property itself, or its `items` for an array of scalars (`type: [String]`).
265
+ camelCase keys (`minLength`, `readOnly`, …) are accepted too.
266
+
179
267
  ---
180
268
 
181
269
  ## Authentication / Security
@@ -199,6 +287,11 @@ doc = GrapeOpenapi3.generate(
199
287
 
200
288
  When `security` is set, a `401 Unauthorized` response is **automatically added** to every endpoint. Routes that explicitly set `security: []` are treated as public and skip the 401.
201
289
 
290
+ > **Server URL:** generated paths already include the Grape `prefix`/`version`
291
+ > (e.g. `/api/v1/products`). The server URL should only add the path where
292
+ > `config/routes.rb` mounts the API (nothing if it's mounted at `/`) — otherwise
293
+ > Swagger UI's "Try it out" calls `/api/v1/api/v1/products`.
294
+
202
295
  ---
203
296
 
204
297
  ## operationId
@@ -213,11 +306,59 @@ Every operation gets a unique `operationId` automatically derived from the HTTP
213
306
  | PUT | `/products/{id}` | `updateProduct` |
214
307
  | DELETE | `/products/{id}` | `deleteProduct` |
215
308
  | GET | `/products/{id}/images` | `listProductImages` |
309
+ | PATCH | `/products/{id}` (next to a PUT) | `patchProduct` |
310
+
311
+ operationIds are always unique: when two operations would get the same id, `PUT`
312
+ keeps `update…` and the other falls back to its HTTP verb (then a numeric suffix).
313
+ Set one explicitly with `nickname:` (or `operation_id:`):
314
+
315
+ ```ruby
316
+ desc "Publish a product", nickname: "publishProduct"
317
+ ```
216
318
 
217
319
  This makes Postman imports, SDK generators, and Redoc anchors work out of the box.
218
320
 
219
321
  ---
220
322
 
323
+ ## Strict mode
324
+
325
+ By default, anything the generator can't type is documented as a `string`
326
+ without complaint. Strict mode reports those gaps instead:
327
+
328
+ ```ruby
329
+ GrapeOpenapi3.generate(API, info: { … }, strict: :warn) # one warning per gap on stderr
330
+ GrapeOpenapi3.generate(API, info: { … }, strict: true) # raises GrapeOpenapi3::StrictModeError
331
+ ```
332
+
333
+ ```
334
+ ProductEntity.created_at: no documentation type — documented as string
335
+ ProductEntity.amount: unknown type Money — documented as string
336
+ ProductEntity.owner: using: Missing::Entity cannot be resolved — documented as object
337
+ ProductEntity.stats.views: no documentation type — documented as string
338
+ GET /products/{id}: param id has no type — documented as string
339
+ GET /health: 200 response has no schema
340
+ ```
341
+
342
+ A good setup is `strict: true` in CI / your rake task and the default in the
343
+ live endpoint. An unresolvable `using:` is always emitted as a plain object
344
+ (never a broken `$ref`), strict or not.
345
+
346
+ ---
347
+
348
+ ## Testing your docs
349
+
350
+ `example/rails_app/spec/` shows a contract-test pattern worth copying: call every
351
+ endpoint for real and validate each response body against the generated document
352
+ with [`json_schemer`](https://github.com/davishmcclurg/json_schemer), in strict
353
+ mode (`additionalProperties: false` on the test copy), so a field the API returns
354
+ but the entity doesn't declare fails the build:
355
+
356
+ ```ruby
357
+ expect(response).to match_openapi_contract("get", "/api/v1/products/{id}")
358
+ ```
359
+
360
+ ---
361
+
221
362
  ## Rails integration
222
363
 
223
364
  ### Generate the rake task
@@ -265,11 +406,15 @@ Rails serves `public/` as static files automatically. Navigate to `http://localh
265
406
  The `example/rails_app/` folder is a complete, runnable **Rails 8 + Grape** API you
266
407
  can use to see everything in action. It models a small real-world domain:
267
408
 
268
- - **`Product`** — CRUD resource (`/api/v1/products`)
269
- - **`Category`** — `Product belongs_to :category`, exposed as a **nested entity**
409
+ - **`Product`** — CRUD resource (`/api/v1/products`) with `PUT` and `PATCH`,
410
+ paginated/filterable/sortable list, param constraints and a documented header
411
+ - **`Category`** — `Product belongs_to :category`, exposed as a **nullable nested entity**;
412
+ `/api/v1/categories` (conditional `products_count`) and `/categories/{id}/products`
270
413
  - **Typed errors** — `404`/`422` responses carry `ErrorEntity` / `ValidationErrorEntity`
271
414
  - **Live docs** — the OpenAPI JSON is served dynamically by a mounted endpoint
272
415
  (`V1::OpenapiDoc`), no build step required
416
+ - **Contract tests** — every endpoint called for real and validated against the doc,
417
+ plus a strict-mode check
273
418
 
274
419
  ### Run it
275
420
 
@@ -278,6 +423,7 @@ cd example/rails_app
278
423
  bundle install
279
424
  bin/rails db:prepare # create + migrate + seed (5 categories, 20 products)
280
425
  bin/rails server
426
+ bundle exec rspec # contract tests
281
427
  ```
282
428
 
283
429
  ### What to open
@@ -290,8 +436,10 @@ bin/rails server
290
436
 
291
437
  ### Things to notice in the docs
292
438
 
293
- - `ProductEntity.category` is a `$ref` to `CategoryEntity` (the `belongs_to`).
294
- - `POST /api/v1/products` shows the `404`/`422` responses with **typed bodies**.
439
+ - `ProductEntity.category` is a nullable `$ref` to `CategoryEntity` (the `belongs_to`).
440
+ - `POST /api/v1/products` shows the `422` response with a **typed body**, and its
441
+ params carry `minLength`/`maxLength`/`minimum` from the Grape validations.
442
+ - `PUT` and `PATCH /api/v1/products/{id}` get distinct operationIds.
295
443
  - Edit an entity or route, refresh `/swagger.html` — the doc updates immediately
296
444
  (it's generated per request; no rake step needed).
297
445
 
@@ -300,13 +448,18 @@ bin/rails server
300
448
  If you'd rather serve a static file (e.g. for hosting), there's also a rake task:
301
449
 
302
450
  ```bash
303
- bundle exec rake openapi:generate # writes public/openapi.json
304
- OPENAPI_SERVER_URL=https://api.example.com/api/v1 bundle exec rake openapi:generate
451
+ bundle exec rake openapi:generate # writes public/openapi.json (strict mode)
452
+ OPENAPI_SERVER_URL=https://api.example.com bundle exec rake openapi:generate
305
453
  ```
306
454
 
307
455
  There's also a dependency-free plain-Grape example at `example/` (run
308
- `bundle exec ruby example/generate.rb` to produce `example/openapi.json`), which
309
- additionally showcases nested params and the collision-free schema naming.
456
+ `bundle exec ruby example/generate.rb` to produce `example/openapi.json`). It is
457
+ the **catalog of every feature** — each line of `example/api.rb` and
458
+ `example/entities.rb` is commented with what it becomes in the doc: nested and
459
+ array-of-object params, multipart uploads, multiple success responses, block /
460
+ merged / conditional exposures, every documentation keyword, variant and JSON
461
+ types, `nickname:`, a public `security: []` route and collision-free schema naming.
462
+ It is generated with `strict: true`.
310
463
 
311
464
  ---
312
465
 
@@ -314,15 +467,25 @@ additionally showcases nested params and the collision-free schema naming.
314
467
 
315
468
  | Ruby / Grape type | OpenAPI schema |
316
469
  |---|---|
317
- | `String` | `{ "type": "string" }` |
470
+ | `String` / `Symbol` | `{ "type": "string" }` |
318
471
  | `Integer` | `{ "type": "integer" }` |
319
- | `Float` / `BigDecimal` | `{ "type": "number", "format": "float" }` |
472
+ | `Float` | `{ "type": "number", "format": "float" }` |
473
+ | `BigDecimal` | `{ "type": "number", "format": "double" }` |
474
+ | `Numeric` | `{ "type": "number" }` |
320
475
  | `Date` | `{ "type": "string", "format": "date" }` |
321
476
  | `DateTime` / `Time` | `{ "type": "string", "format": "date-time" }` |
322
477
  | `Grape::API::Boolean` / `:boolean` | `{ "type": "boolean" }` |
323
- | `File` | `{ "type": "string", "format": "binary" }` |
478
+ | `File` | `{ "type": "string", "format": "binary" }` (multipart body) |
324
479
  | `Hash` | `{ "type": "object" }` |
325
- | `[String]` / `[Integer]` | `{ "type": "array", "items": { ... } }` |
480
+ | `JSON` | `{ "oneOf": [object, array of objects] }` |
481
+ | `[String]` / `Array[Integer]` | `{ "type": "array", "items": { ... } }` |
482
+ | `[Integer, String]` / `types: [...]` | `{ "oneOf": [ ... ] }` |
483
+ | `"string"`, `"integer"`, `"number"`, `"boolean"`, `"object"`, `"array"` | the same OpenAPI type |
484
+
485
+ Anything else is documented as `string` — use [strict mode](#strict-mode) to catch it.
486
+
487
+ > A `BigDecimal` attribute serializes to a JSON **string** (`"29.9"`). If an entity
488
+ > documents it as a number, convert it: `expose(:price, documentation: { type: Float }) { |p, _| p.price.to_f }`.
326
489
 
327
490
  ---
328
491
 
@@ -5,13 +5,17 @@ namespace :openapi do
5
5
  Generate OpenAPI 3.0 JSON documentation.
6
6
 
7
7
  ENV vars (all optional):
8
- OPENAPI_SERVER_URL — server URL (default: http://localhost:3000/api)
8
+ OPENAPI_SERVER_URL — server URL (default: http://localhost:3000).
9
+ Generated paths already include the Grape `prefix`/`version`
10
+ (e.g. /api/v1/...) — don't repeat them here. Only add the
11
+ path where config/routes.rb mounts the API, if it isn't "/"
12
+ (e.g. `mount MyApi => "/api"` → http://localhost:3000/api).
9
13
  OPENAPI_OUTPUT_PATH — output file path (default: public/openapi.json)
10
14
  OPENAPI_TITLE — API title
11
15
  OPENAPI_VERSION — API version (default: v1)
12
16
 
13
17
  Example:
14
- OPENAPI_SERVER_URL=https://api.example.com/api bundle exec rake openapi:generate
18
+ OPENAPI_SERVER_URL=https://api.example.com bundle exec rake openapi:generate
15
19
  DESC
16
20
  task generate: :environment do
17
21
  require "json"
@@ -29,7 +33,7 @@ namespace :openapi do
29
33
  },
30
34
  servers: [
31
35
  {
32
- url: ENV.fetch("OPENAPI_SERVER_URL", "http://localhost:3000/api"),
36
+ url: ENV.fetch("OPENAPI_SERVER_URL", "http://localhost:3000"),
33
37
  description: "Server",
34
38
  },
35
39
  ],
@@ -42,6 +46,9 @@ namespace :openapi do
42
46
  },
43
47
  },
44
48
  security: [{ Bearer: [] }],
49
+ # Report documentation gaps (untyped fields/params, unknown types, …).
50
+ # Use `true` to fail the task instead of warning.
51
+ strict: :warn,
45
52
  )
46
53
  # ── End config ────────────────────────────────────────────────────────────
47
54
 
@@ -6,21 +6,22 @@ module GrapeOpenapi3
6
6
  # Delegates parameter building to ParameterBuilder and
7
7
  # registers any Grape::Entity response classes with the EntityReader.
8
8
  class OperationBuilder
9
- def self.call(route_data, entity_reader, global_security: false)
10
- new(route_data, entity_reader, global_security: global_security).call
9
+ def self.call(route_data, entity_reader, global_security: false, diagnostics: Diagnostics.new)
10
+ new(route_data, entity_reader, global_security: global_security, diagnostics: diagnostics).call
11
11
  end
12
12
 
13
- def initialize(route_data, entity_reader, global_security: false)
13
+ def initialize(route_data, entity_reader, global_security: false, diagnostics: Diagnostics.new)
14
14
  @route = route_data
15
15
  @entity_reader = entity_reader
16
16
  @global_security = global_security
17
+ @diagnostics = diagnostics
17
18
  end
18
19
 
19
20
  def call
20
- param_result = ParameterBuilder.call(@route)
21
+ param_result = ParameterBuilder.call(@route, diagnostics: @diagnostics)
21
22
 
22
23
  operation = {}
23
- operation["operationId"] = OperationIdBuilder.call(@route[:http_method], @route[:path])
24
+ operation["operationId"] = @route[:operation_id] || OperationIdBuilder.call(@route[:http_method], @route[:path])
24
25
  operation["summary"] = @route[:summary] if @route[:summary]
25
26
  operation["description"] = @route[:detail] if @route[:detail]
26
27
  operation["tags"] = @route[:tags] unless @route[:tags].empty?
@@ -37,11 +38,15 @@ module GrapeOpenapi3
37
38
 
38
39
  def build_responses
39
40
  responses = {}
40
- responses[success_code] = build_success_response
41
+ success_entries.each do |entity|
42
+ code = success_code(entity)
43
+ responses[code] = build_success_response(entity)
44
+ report_missing_schema(code, responses[code])
45
+ end
41
46
 
42
47
  @route[:failure_codes].each do |info|
43
48
  code = (info[:code] || info["code"]).to_s
44
- responses[code] = build_failure_response(info)
49
+ responses[code] = build_failure_response(info, code)
45
50
  end
46
51
 
47
52
  # Add 401 automatically when the API uses security and the route hasn't
@@ -53,8 +58,21 @@ module GrapeOpenapi3
53
58
  responses
54
59
  end
55
60
 
56
- def success_code
61
+ # A 200 almost always has a body; 201/202/204 without one are legitimate.
62
+ def report_missing_schema(code, response)
63
+ return unless code == "200" && !response.key?("content")
64
+
65
+ @diagnostics.report("#{@route[:http_method].upcase} #{@route[:path]}", "200 response has no schema")
66
+ end
67
+
68
+ # `success:` is a single entity/hash, or an Array of hashes for several
69
+ # success codes: [{ code: 200, model: X }, { code: 202, message: "Queued" }]
70
+ def success_entries
57
71
  entity = @route[:success_entity]
72
+ entity.is_a?(Array) && !entity.empty? ? entity : [entity]
73
+ end
74
+
75
+ def success_code(entity)
58
76
  return "204" if entity.nil? && @route[:http_method] == "delete"
59
77
 
60
78
  # Explicit code in success hash always wins
@@ -76,21 +94,24 @@ module GrapeOpenapi3
76
94
  true
77
95
  end
78
96
 
79
- def build_success_response
80
- entity = @route[:success_entity]
97
+ def build_success_response(entity)
98
+ return { "description" => "No Content" } if entity.nil? && @route[:http_method] == "delete"
81
99
  return { "description" => "Success" } unless entity
82
100
 
83
101
  # Unpack hash form: { code: 201, message: "Created", model: ProductEntity, schema: {...} }
84
102
  description, entity_class, inline_schema = unpack_success(entity)
85
- build_response(description, entity_class, inline_schema, is_array: @route[:is_array])
103
+ is_array = @route[:is_array] || (entity.is_a?(Hash) && (entity[:is_array] || entity["is_array"])) || false
104
+ build_response(description, entity_class, inline_schema, is_array: is_array)
86
105
  end
87
106
 
88
107
  # A failure entry may carry a typed body, e.g.
89
108
  # failure: [{ code: 422, message: "Validation error", model: ErrorEntity }]
90
109
  # failure: [{ code: 404, message: "Not found", schema: { ... } }]
91
110
  # Without :model/:schema it stays a bare { "description" => message }.
92
- def build_failure_response(info)
93
- message = info[:message] || info["message"] || ""
111
+ # Without a message the description falls back to the HTTP reason phrase.
112
+ def build_failure_response(info, code)
113
+ message = (info[:message] || info["message"]).to_s
114
+ message = reason_phrase(code) if message.strip.empty?
94
115
  model = info[:model] || info["model"]
95
116
  inline_schema = info[:schema] || info["schema"]
96
117
  is_array = info[:is_array] || info["is_array"] || false
@@ -98,6 +119,12 @@ module GrapeOpenapi3
98
119
  build_response(message, (model if model.is_a?(Class)), inline_schema, is_array: is_array)
99
120
  end
100
121
 
122
+ # OpenAPI requires a non-empty description on every response.
123
+ def reason_phrase(code)
124
+ phrase = Rack::Utils::HTTP_STATUS_CODES[code.to_i] if defined?(Rack::Utils::HTTP_STATUS_CODES)
125
+ phrase || "Response #{code}"
126
+ end
127
+
101
128
  # Shared builder for success and failure responses.
102
129
  def build_response(description, entity_class, inline_schema, is_array:)
103
130
  media = @route[:produces].first || "application/json"
@@ -25,13 +25,16 @@ module GrapeOpenapi3
25
25
  "delete" => ->(_) { "delete" },
26
26
  }.freeze
27
27
 
28
- def self.call(http_method, path)
29
- new(http_method, path).call
28
+ # action: overrides the derived verb (e.g. "patch" → patchProduct). Used by
29
+ # Document to disambiguate operations that would otherwise share an id.
30
+ def self.call(http_method, path, action: nil)
31
+ new(http_method, path, action: action).call
30
32
  end
31
33
 
32
- def initialize(http_method, path)
34
+ def initialize(http_method, path, action: nil)
33
35
  @method = http_method.downcase
34
36
  @path = path
37
+ @action = action
35
38
  end
36
39
 
37
40
  def call
@@ -47,7 +50,7 @@ module GrapeOpenapi3
47
50
 
48
51
  return fallback if resources.empty?
49
52
 
50
- action = ACTIONS.fetch(@method, ->(_) { @method }).call(trailing_param)
53
+ action = @action || ACTIONS.fetch(@method, ->(_) { @method }).call(trailing_param)
51
54
  # For known verbs, "list" signals a collection. For unknown verbs (HEAD, OPTIONS…),
52
55
  # infer from path: no trailing param means collection → keep last segment plural.
53
56
  collection = action == "list" || (!ACTIONS.key?(@method) && !trailing_param)