grape_openapi3 0.1.5 → 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: c028381878b52f6a689b843e5e0b4aa37799bc26fc612316b51a6617783f4afa
4
- data.tar.gz: b72d1e69efff1e6575cb72c2d1fae4c2a09d5a908f5e809a7c3b8303f681c4b8
3
+ metadata.gz: 4d46572297963e73804e00ac25c1c26ca92830c6f54efc95e472ac07d8a8c88d
4
+ data.tar.gz: 116e9f799e622500af92fc255fd766a5a39e48cf02bff7fdc474bd49a627204e
5
5
  SHA512:
6
- metadata.gz: 7908a7ac38deeeda95246ee30026f82b9f3c872ff26c4c8863de6b2f9a6157963d5230235bc616593b761603ce3291ee4608711417e88085ff5430f99e4f6c17
7
- data.tar.gz: '089da884741c789d424e8e11f55814b20ef2025567ba08b9c9f4a7231e4980fd306d5e6d621b8fcec1490faa0bcedc278b4b1325a1696a627966ae650d44316a'
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,38 @@ 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
+ ]
121
+ ```
122
+
123
+ A `DELETE` without a success entity is documented as `204 No Content`.
124
+
125
+ ### Failure options (typed error responses)
126
+
127
+ Error responses can carry a schema too — point them at a `Grape::Entity` with
128
+ `model:` (or an inline OpenAPI schema with `schema:`). Without either, a failure
129
+ stays a plain description.
130
+
131
+ ```ruby
132
+ failure: [
133
+ { code: 401, message: "Unauthorized" }, # description only
134
+ { code: 404, message: "Not found", model: Entities::ErrorEntity }, # $ref to a schema
135
+ { code: 422, message: "Validation", model: Entities::ValidationErrorEntity },
136
+ { code: 409, message: "Conflict", schema: { type: "object", properties: { code: { type: "string" } } } },
137
+ [429], # no message → "Too Many Requests"
138
+ ]
108
139
  ```
109
140
 
141
+ This lets an OpenAPI → TypeScript/Zod codegen type your error payloads, not just
142
+ the success body.
143
+
110
144
  ### Params via params do block
111
145
 
112
146
  ```ruby
@@ -121,6 +155,39 @@ end
121
155
  ```
122
156
 
123
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.
124
191
 
125
192
  ---
126
193
 
@@ -148,6 +215,11 @@ class OrderEntity < Grape::Entity
148
215
  end
149
216
  ```
150
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
+
151
223
  Array responses via `is_array: true`:
152
224
 
153
225
  ```ruby
@@ -158,6 +230,40 @@ class ProductListEntity < Grape::Entity
158
230
  end
159
231
  ```
160
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
+
161
267
  ---
162
268
 
163
269
  ## Authentication / Security
@@ -181,6 +287,11 @@ doc = GrapeOpenapi3.generate(
181
287
 
182
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.
183
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
+
184
295
  ---
185
296
 
186
297
  ## operationId
@@ -195,11 +306,59 @@ Every operation gets a unique `operationId` automatically derived from the HTTP
195
306
  | PUT | `/products/{id}` | `updateProduct` |
196
307
  | DELETE | `/products/{id}` | `deleteProduct` |
197
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
+ ```
198
318
 
199
319
  This makes Postman imports, SDK generators, and Redoc anchors work out of the box.
200
320
 
201
321
  ---
202
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
+
203
362
  ## Rails integration
204
363
 
205
364
  ### Generate the rake task
@@ -244,39 +403,89 @@ Rails serves `public/` as static files automatically. Navigate to `http://localh
244
403
 
245
404
  ## Example project
246
405
 
247
- The `example/rails_app/` folder contains a full Rails 8 + Grape API with a products CRUD — the same setup described in this README, ready to run:
406
+ The `example/rails_app/` folder is a complete, runnable **Rails 8 + Grape** API you
407
+ can use to see everything in action. It models a small real-world domain:
408
+
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`
413
+ - **Typed errors** — `404`/`422` responses carry `ErrorEntity` / `ValidationErrorEntity`
414
+ - **Live docs** — the OpenAPI JSON is served dynamically by a mounted endpoint
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
418
+
419
+ ### Run it
248
420
 
249
421
  ```bash
250
422
  cd example/rails_app
251
423
  bundle install
252
- rails db:create db:migrate db:seed
253
- rails server
424
+ bin/rails db:prepare # create + migrate + seed (5 categories, 20 products)
425
+ bin/rails server
426
+ bundle exec rspec # contract tests
427
+ ```
254
428
 
255
- # API live at:
256
- # http://localhost:3000/api/v1/products
429
+ ### What to open
257
430
 
258
- # Generate the docs:
259
- bundle exec rake openapi:generate
431
+ | URL | What you get |
432
+ |---|---|
433
+ | `http://localhost:3000/swagger.html` | **Swagger UI** — browse and try every endpoint |
434
+ | `http://localhost:3000/api/v1/openapi` | the **OpenAPI 3.0 JSON**, generated live from the routes |
435
+ | `http://localhost:3000/api/v1/products` | the actual API — note `category` comes back as `{ id, name }` |
260
436
 
261
- # View Swagger UI:
262
- # http://localhost:3000/swagger.html
437
+ ### Things to notice in the docs
438
+
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.
443
+ - Edit an entity or route, refresh `/swagger.html` — the doc updates immediately
444
+ (it's generated per request; no rake step needed).
445
+
446
+ ### Static doc (optional)
447
+
448
+ If you'd rather serve a static file (e.g. for hosting), there's also a rake task:
449
+
450
+ ```bash
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
263
453
  ```
264
454
 
455
+ There's also a dependency-free plain-Grape example at `example/` (run
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`.
463
+
265
464
  ---
266
465
 
267
466
  ## Type reference
268
467
 
269
468
  | Ruby / Grape type | OpenAPI schema |
270
469
  |---|---|
271
- | `String` | `{ "type": "string" }` |
470
+ | `String` / `Symbol` | `{ "type": "string" }` |
272
471
  | `Integer` | `{ "type": "integer" }` |
273
- | `Float` / `BigDecimal` | `{ "type": "number", "format": "float" }` |
472
+ | `Float` | `{ "type": "number", "format": "float" }` |
473
+ | `BigDecimal` | `{ "type": "number", "format": "double" }` |
474
+ | `Numeric` | `{ "type": "number" }` |
274
475
  | `Date` | `{ "type": "string", "format": "date" }` |
275
476
  | `DateTime` / `Time` | `{ "type": "string", "format": "date-time" }` |
276
477
  | `Grape::API::Boolean` / `:boolean` | `{ "type": "boolean" }` |
277
- | `File` | `{ "type": "string", "format": "binary" }` |
478
+ | `File` | `{ "type": "string", "format": "binary" }` (multipart body) |
278
479
  | `Hash` | `{ "type": "object" }` |
279
- | `[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 }`.
280
489
 
281
490
  ---
282
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,12 +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
- code = (info[:code] || info["code"]).to_s
44
- message = info[:message] || info["message"] || ""
45
- responses[code] = { "description" => message }
48
+ code = (info[:code] || info["code"]).to_s
49
+ responses[code] = build_failure_response(info, code)
46
50
  end
47
51
 
48
52
  # Add 401 automatically when the API uses security and the route hasn't
@@ -54,8 +58,21 @@ module GrapeOpenapi3
54
58
  responses
55
59
  end
56
60
 
57
- 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
58
71
  entity = @route[:success_entity]
72
+ entity.is_a?(Array) && !entity.empty? ? entity : [entity]
73
+ end
74
+
75
+ def success_code(entity)
59
76
  return "204" if entity.nil? && @route[:http_method] == "delete"
60
77
 
61
78
  # Explicit code in success hash always wins
@@ -77,28 +94,52 @@ module GrapeOpenapi3
77
94
  true
78
95
  end
79
96
 
80
- def build_success_response
81
- entity = @route[:success_entity]
97
+ def build_success_response(entity)
98
+ return { "description" => "No Content" } if entity.nil? && @route[:http_method] == "delete"
82
99
  return { "description" => "Success" } unless entity
83
100
 
84
101
  # Unpack hash form: { code: 201, message: "Created", model: ProductEntity, schema: {...} }
85
102
  description, entity_class, inline_schema = unpack_success(entity)
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)
105
+ end
106
+
107
+ # A failure entry may carry a typed body, e.g.
108
+ # failure: [{ code: 422, message: "Validation error", model: ErrorEntity }]
109
+ # failure: [{ code: 404, message: "Not found", schema: { ... } }]
110
+ # Without :model/:schema it stays a bare { "description" => 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?
115
+ model = info[:model] || info["model"]
116
+ inline_schema = info[:schema] || info["schema"]
117
+ is_array = info[:is_array] || info["is_array"] || false
118
+
119
+ build_response(message, (model if model.is_a?(Class)), inline_schema, is_array: is_array)
120
+ end
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
+
128
+ # Shared builder for success and failure responses.
129
+ def build_response(description, entity_class, inline_schema, is_array:)
130
+ media = @route[:produces].first || "application/json"
86
131
 
87
132
  if inline_schema
88
- media = @route[:produces].first || "application/json"
89
133
  return { "description" => description, "content" => { media => { "schema" => inline_schema } } }
90
134
  end
91
135
 
92
- unless entity_class
93
- return { "description" => description }
94
- end
136
+ return { "description" => description } unless entity_class
95
137
 
96
138
  schema_name = @entity_reader.register(entity_class)
97
139
  return { "description" => description } unless schema_name
98
140
 
99
141
  ref = { "$ref" => "#/components/schemas/#{schema_name}" }
100
- schema = @route[:is_array] ? { "type" => "array", "items" => ref } : ref
101
- media = @route[:produces].first || "application/json"
142
+ schema = is_array ? { "type" => "array", "items" => ref } : ref
102
143
 
103
144
  { "description" => description, "content" => { media => { "schema" => schema } } }
104
145
  end