grape 2.0.0 → 2.2.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/CHANGELOG.md +96 -1
- data/README.md +364 -317
- data/UPGRADING.md +205 -7
- data/grape.gemspec +7 -7
- data/lib/grape/api/instance.rb +14 -11
- data/lib/grape/api.rb +19 -10
- data/lib/grape/content_types.rb +13 -10
- data/lib/grape/cookies.rb +2 -1
- data/lib/grape/dry_types.rb +0 -2
- data/lib/grape/dsl/desc.rb +22 -20
- data/lib/grape/dsl/headers.rb +1 -1
- data/lib/grape/dsl/helpers.rb +7 -3
- data/lib/grape/dsl/inside_route.rb +51 -15
- data/lib/grape/dsl/parameters.rb +5 -4
- data/lib/grape/dsl/request_response.rb +14 -18
- data/lib/grape/dsl/routing.rb +20 -4
- data/lib/grape/dsl/validations.rb +13 -0
- data/lib/grape/endpoint.rb +43 -35
- data/lib/grape/{util/env.rb → env.rb} +0 -5
- data/lib/grape/error_formatter/json.rb +13 -4
- data/lib/grape/error_formatter/txt.rb +11 -10
- data/lib/grape/error_formatter.rb +13 -25
- data/lib/grape/exceptions/base.rb +3 -3
- data/lib/grape/exceptions/validation.rb +0 -2
- data/lib/grape/exceptions/validation_array_errors.rb +1 -0
- data/lib/grape/exceptions/validation_errors.rb +2 -4
- data/lib/grape/extensions/hash.rb +5 -1
- data/lib/grape/formatter.rb +15 -25
- data/lib/grape/http/headers.rb +18 -34
- data/lib/grape/{util/json.rb → json.rb} +1 -3
- data/lib/grape/locale/en.yml +4 -0
- data/lib/grape/middleware/auth/base.rb +0 -2
- data/lib/grape/middleware/auth/dsl.rb +0 -2
- data/lib/grape/middleware/base.rb +14 -15
- data/lib/grape/middleware/error.rb +61 -54
- data/lib/grape/middleware/formatter.rb +18 -15
- data/lib/grape/middleware/globals.rb +1 -3
- data/lib/grape/middleware/stack.rb +4 -5
- data/lib/grape/middleware/versioner/accept_version_header.rb +8 -33
- data/lib/grape/middleware/versioner/header.rb +62 -123
- data/lib/grape/middleware/versioner/param.rb +5 -23
- data/lib/grape/middleware/versioner/path.rb +11 -33
- data/lib/grape/middleware/versioner.rb +5 -14
- data/lib/grape/middleware/versioner_helpers.rb +75 -0
- data/lib/grape/namespace.rb +3 -4
- data/lib/grape/parser.rb +8 -24
- data/lib/grape/path.rb +24 -29
- data/lib/grape/request.rb +4 -12
- data/lib/grape/router/base_route.rb +39 -0
- data/lib/grape/router/greedy_route.rb +20 -0
- data/lib/grape/router/pattern.rb +39 -30
- data/lib/grape/router/route.rb +22 -59
- data/lib/grape/router.rb +32 -37
- data/lib/grape/util/base_inheritable.rb +4 -4
- data/lib/grape/util/cache.rb +0 -3
- data/lib/grape/util/endpoint_configuration.rb +1 -1
- data/lib/grape/util/header.rb +13 -0
- data/lib/grape/util/inheritable_values.rb +0 -2
- data/lib/grape/util/lazy/block.rb +29 -0
- data/lib/grape/util/lazy/object.rb +45 -0
- data/lib/grape/util/lazy/value.rb +38 -0
- data/lib/grape/util/lazy/value_array.rb +21 -0
- data/lib/grape/util/lazy/value_enumerable.rb +34 -0
- data/lib/grape/util/lazy/value_hash.rb +21 -0
- data/lib/grape/util/media_type.rb +70 -0
- data/lib/grape/util/reverse_stackable_values.rb +1 -6
- data/lib/grape/util/stackable_values.rb +1 -6
- data/lib/grape/util/strict_hash_configuration.rb +3 -3
- data/lib/grape/validations/attributes_doc.rb +38 -36
- data/lib/grape/validations/attributes_iterator.rb +1 -0
- data/lib/grape/validations/contract_scope.rb +71 -0
- data/lib/grape/validations/params_scope.rb +22 -19
- data/lib/grape/validations/types/array_coercer.rb +0 -2
- data/lib/grape/validations/types/build_coercer.rb +69 -71
- data/lib/grape/validations/types/dry_type_coercer.rb +1 -11
- data/lib/grape/validations/types/json.rb +0 -2
- data/lib/grape/validations/types/primitive_coercer.rb +0 -2
- data/lib/grape/validations/types/set_coercer.rb +0 -3
- data/lib/grape/validations/types.rb +0 -3
- data/lib/grape/validations/validators/base.rb +1 -0
- data/lib/grape/validations/validators/default_validator.rb +5 -1
- data/lib/grape/validations/validators/exactly_one_of_validator.rb +1 -1
- data/lib/grape/validations/validators/length_validator.rb +49 -0
- data/lib/grape/validations/validators/values_validator.rb +6 -1
- data/lib/grape/validations.rb +3 -7
- data/lib/grape/version.rb +1 -1
- data/lib/grape/{util/xml.rb → xml.rb} +1 -1
- data/lib/grape.rb +30 -274
- metadata +31 -38
- data/lib/grape/eager_load.rb +0 -20
- data/lib/grape/middleware/versioner/parse_media_type_patch.rb +0 -24
- data/lib/grape/router/attribute_translator.rb +0 -63
- data/lib/grape/util/lazy_block.rb +0 -27
- data/lib/grape/util/lazy_object.rb +0 -43
- data/lib/grape/util/lazy_value.rb +0 -91
- data/lib/grape/util/registrable.rb +0 -15
data/README.md
CHANGED
@@ -19,21 +19,18 @@
|
|
19
19
|
- [Mounting](#mounting)
|
20
20
|
- [All](#all)
|
21
21
|
- [Rack](#rack)
|
22
|
-
- [ActiveRecord without Rails](#activerecord-without-rails)
|
23
|
-
- [Rails 4](#rails-4)
|
24
|
-
- [Rails 5+](#rails-5)
|
25
22
|
- [Alongside Sinatra (or other frameworks)](#alongside-sinatra-or-other-frameworks)
|
26
23
|
- [Rails](#rails)
|
27
|
-
- [
|
28
|
-
- [Rails 6.0](#rails-60)
|
24
|
+
- [Zeitwerk](#zeitwerk)
|
29
25
|
- [Modules](#modules)
|
30
26
|
- [Remounting](#remounting)
|
31
27
|
- [Mount Configuration](#mount-configuration)
|
32
28
|
- [Versioning](#versioning)
|
33
|
-
- [
|
34
|
-
|
35
|
-
|
36
|
-
|
29
|
+
- [Strategies](#strategies)
|
30
|
+
- [Path](#path)
|
31
|
+
- [Header](#header)
|
32
|
+
- [Accept-Version Header](#accept-version-header)
|
33
|
+
- [Param](#param)
|
37
34
|
- [Describing Methods](#describing-methods)
|
38
35
|
- [Configuration](#configuration)
|
39
36
|
- [Parameters](#parameters)
|
@@ -42,6 +39,7 @@
|
|
42
39
|
- [Include Parent Namespaces](#include-parent-namespaces)
|
43
40
|
- [Include Missing](#include-missing)
|
44
41
|
- [Evaluate Given](#evaluate-given)
|
42
|
+
- [Parameter Precedence](#parameter-precedence)
|
45
43
|
- [Parameter Validation and Coercion](#parameter-validation-and-coercion)
|
46
44
|
- [Supported Parameter Types](#supported-parameter-types)
|
47
45
|
- [Integer/Fixnum and Coercions](#integerfixnum-and-coercions)
|
@@ -58,6 +56,7 @@
|
|
58
56
|
- [values](#values)
|
59
57
|
- [except_values](#except_values)
|
60
58
|
- [same_as](#same_as)
|
59
|
+
- [length](#length)
|
61
60
|
- [regexp](#regexp)
|
62
61
|
- [mutually_exclusive](#mutually_exclusive)
|
63
62
|
- [exactly_one_of](#exactly_one_of)
|
@@ -71,6 +70,7 @@
|
|
71
70
|
- [Custom Validation messages](#custom-validation-messages)
|
72
71
|
- [presence, allow_blank, values, regexp](#presence-allow_blank-values-regexp)
|
73
72
|
- [same_as](#same_as-1)
|
73
|
+
- [length](#length-1)
|
74
74
|
- [all_or_none_of](#all_or_none_of-1)
|
75
75
|
- [mutually_exclusive](#mutually_exclusive-1)
|
76
76
|
- [exactly_one_of](#exactly_one_of-1)
|
@@ -80,6 +80,7 @@
|
|
80
80
|
- [Pass symbols for i18n translations](#pass-symbols-for-i18n-translations)
|
81
81
|
- [Overriding Attribute Names](#overriding-attribute-names)
|
82
82
|
- [With Default](#with-default)
|
83
|
+
- [Using dry-validation or dry-schema](#using-dry-validation-or-dry-schema)
|
83
84
|
- [Headers](#headers)
|
84
85
|
- [Request](#request)
|
85
86
|
- [Header Case Handling](#header-case-handling)
|
@@ -100,7 +101,6 @@
|
|
100
101
|
- [Rescuing exceptions inside namespaces](#rescuing-exceptions-inside-namespaces)
|
101
102
|
- [Unrescuable Exceptions](#unrescuable-exceptions)
|
102
103
|
- [Exceptions that should be rescued explicitly](#exceptions-that-should-be-rescued-explicitly)
|
103
|
-
- [Rails 3.x](#rails-3x)
|
104
104
|
- [Logging](#logging)
|
105
105
|
- [API Formats](#api-formats)
|
106
106
|
- [JSONP](#jsonp)
|
@@ -121,6 +121,7 @@
|
|
121
121
|
- [Current Route and Endpoint](#current-route-and-endpoint)
|
122
122
|
- [Before, After and Finally](#before-after-and-finally)
|
123
123
|
- [Anchoring](#anchoring)
|
124
|
+
- [Instance Variables](#instance-variables)
|
124
125
|
- [Using Custom Middleware](#using-custom-middleware)
|
125
126
|
- [Grape Middleware](#grape-middleware)
|
126
127
|
- [Rails Middleware](#rails-middleware)
|
@@ -152,17 +153,11 @@
|
|
152
153
|
|
153
154
|
## What is Grape?
|
154
155
|
|
155
|
-
Grape is a REST-like API framework for Ruby. It's designed to run on Rack
|
156
|
-
or complement existing web application frameworks such as Rails and Sinatra by
|
157
|
-
providing a simple DSL to easily develop RESTful APIs. It has built-in support
|
158
|
-
for common conventions, including multiple formats, subdomain/prefix restriction,
|
159
|
-
content negotiation, versioning and much more.
|
156
|
+
Grape is a REST-like API framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs. It has built-in support for common conventions, including multiple formats, subdomain/prefix restriction, content negotiation, versioning and much more.
|
160
157
|
|
161
158
|
## Stable Release
|
162
159
|
|
163
|
-
You're reading the documentation for the stable release of Grape,
|
164
|
-
Please read [UPGRADING](UPGRADING.md) when upgrading from a previous version.
|
165
|
-
|
160
|
+
You're reading the documentation for the stable release of Grape, 2.2.0. Please read UPGRADING when upgrading from a previous version.
|
166
161
|
|
167
162
|
## Project Resources
|
168
163
|
|
@@ -179,7 +174,7 @@ The maintainers of Grape are working with Tidelift to deliver commercial support
|
|
179
174
|
|
180
175
|
## Installation
|
181
176
|
|
182
|
-
Ruby 2.
|
177
|
+
Ruby 2.7 or newer is required.
|
183
178
|
|
184
179
|
Grape is available as a gem, to install it run:
|
185
180
|
|
@@ -188,8 +183,7 @@ Grape is available as a gem, to install it run:
|
|
188
183
|
## Basic Usage
|
189
184
|
|
190
185
|
Grape APIs are Rack applications that are created by subclassing `Grape::API`.
|
191
|
-
Below is a simple example showing some of the more common features of Grape in
|
192
|
-
the context of recreating parts of the Twitter API.
|
186
|
+
Below is a simple example showing some of the more common features of Grape in the context of recreating parts of the Twitter API.
|
193
187
|
|
194
188
|
```ruby
|
195
189
|
module Twitter
|
@@ -287,8 +281,7 @@ This can be added to your `config.ru` (if using rackup), `application.rb` (if us
|
|
287
281
|
|
288
282
|
### Rack
|
289
283
|
|
290
|
-
The above sample creates a Rack application that can be run from a rackup `config.ru` file
|
291
|
-
with `rackup`:
|
284
|
+
The above sample creates a Rack application that can be run from a rackup `config.ru` file with `rackup`:
|
292
285
|
|
293
286
|
```ruby
|
294
287
|
run Twitter::API
|
@@ -312,32 +305,9 @@ And would respond to the following routes:
|
|
312
305
|
|
313
306
|
Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.
|
314
307
|
|
315
|
-
### ActiveRecord without Rails
|
316
|
-
|
317
|
-
If you want to use ActiveRecord within Grape, you will need to make sure that ActiveRecord's connection pool
|
318
|
-
is handled correctly.
|
319
|
-
|
320
|
-
#### Rails 4
|
321
|
-
|
322
|
-
The easiest way to achieve that is by using ActiveRecord's `ConnectionManagement` middleware in your
|
323
|
-
`config.ru` before mounting Grape, e.g.:
|
324
|
-
|
325
|
-
```ruby
|
326
|
-
use ActiveRecord::ConnectionAdapters::ConnectionManagement
|
327
|
-
```
|
328
|
-
|
329
|
-
#### Rails 5+
|
330
|
-
|
331
|
-
Use [otr-activerecord](https://github.com/jhollinger/otr-activerecord) as follows:
|
332
|
-
|
333
|
-
```ruby
|
334
|
-
use OTR::ActiveRecord::ConnectionManagement
|
335
|
-
```
|
336
|
-
|
337
308
|
### Alongside Sinatra (or other frameworks)
|
338
309
|
|
339
|
-
If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using
|
340
|
-
`Rack::Cascade`:
|
310
|
+
If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using `Rack::Cascade`:
|
341
311
|
|
342
312
|
```ruby
|
343
313
|
# Example config.ru
|
@@ -373,21 +343,8 @@ Modify `config/routes`:
|
|
373
343
|
```ruby
|
374
344
|
mount Twitter::API => '/'
|
375
345
|
```
|
376
|
-
|
377
|
-
|
378
|
-
|
379
|
-
Modify `application.rb`:
|
380
|
-
|
381
|
-
```ruby
|
382
|
-
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
|
383
|
-
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
|
384
|
-
```
|
385
|
-
|
386
|
-
See [below](#reloading-api-changes-in-development) for additional code that enables reloading of API changes in development.
|
387
|
-
|
388
|
-
#### Rails 6.0
|
389
|
-
|
390
|
-
For Rails versions greater than 6.0.0.beta2, `Zeitwerk` autoloader is the default for CRuby. By default `Zeitwerk` inflects `api` as `Api` instead of `API`. To make our example work, you need to uncomment the lines at the bottom of `config/initializers/inflections.rb`, and add `API` as an acronym:
|
346
|
+
#### Zeitwerk
|
347
|
+
Rails's default autoloader is `Zeitwerk`. By default, it inflects `api` as `Api` instead of `API`. To make our example work, you need to uncomment the lines at the bottom of `config/initializers/inflections.rb`, and add `API` as an acronym:
|
391
348
|
|
392
349
|
```ruby
|
393
350
|
ActiveSupport::Inflector.inflections(:en) do |inflect|
|
@@ -397,8 +354,7 @@ end
|
|
397
354
|
|
398
355
|
### Modules
|
399
356
|
|
400
|
-
You can mount multiple API implementations inside another one. These don't have to be
|
401
|
-
different versions, but may be components of the same API.
|
357
|
+
You can mount multiple API implementations inside another one. These don't have to be different versions, but may be components of the same API.
|
402
358
|
|
403
359
|
```ruby
|
404
360
|
class Twitter::API < Grape::API
|
@@ -415,7 +371,7 @@ class Twitter::API < Grape::API
|
|
415
371
|
end
|
416
372
|
```
|
417
373
|
|
418
|
-
|
374
|
+
Declarations as `before/after/rescue_from` can be placed before or after `mount`. In any case they will be inherited.
|
419
375
|
|
420
376
|
```ruby
|
421
377
|
class Twitter::API < Grape::API
|
@@ -423,8 +379,20 @@ class Twitter::API < Grape::API
|
|
423
379
|
header 'X-Base-Header', 'will be defined for all APIs that are mounted below'
|
424
380
|
end
|
425
381
|
|
382
|
+
rescue_from :all do
|
383
|
+
error!({ "error" => "Internal Server Error" }, 500)
|
384
|
+
end
|
385
|
+
|
426
386
|
mount Twitter::Users
|
427
387
|
mount Twitter::Search
|
388
|
+
|
389
|
+
after do
|
390
|
+
clean_cache!
|
391
|
+
end
|
392
|
+
|
393
|
+
rescue_from ZeroDivisionError do
|
394
|
+
error!({ "error" => "Not found" }, 404)
|
395
|
+
end
|
428
396
|
end
|
429
397
|
```
|
430
398
|
|
@@ -555,10 +523,69 @@ end
|
|
555
523
|
|
556
524
|
## Versioning
|
557
525
|
|
558
|
-
|
559
|
-
|
526
|
+
You have the option to provide various versions of your API by establishing a separate `Grape::API` class for each offered version and then integrating them into a primary `Grape::API` class. Ensure that newer versions are mounted before older ones. The default approach to versioning directs the request to the subsequent Rack middleware if a specific version is not found.
|
527
|
+
|
528
|
+
```ruby
|
529
|
+
require 'v1'
|
530
|
+
require 'v2'
|
531
|
+
require 'v3'
|
532
|
+
class App < Grape::API
|
533
|
+
mount V3
|
534
|
+
mount V2
|
535
|
+
mount V1
|
536
|
+
end
|
537
|
+
```
|
538
|
+
|
539
|
+
To maintain the same endpoints from earlier API versions without rewriting them, you can indicate multiple versions within the previous API versions.
|
540
|
+
|
541
|
+
```ruby
|
542
|
+
class V1 < Grape::API
|
543
|
+
version 'v1', 'v2', 'v3'
|
544
|
+
|
545
|
+
get '/foo' do
|
546
|
+
# your code for GET /foo
|
547
|
+
end
|
548
|
+
|
549
|
+
get '/other' do
|
550
|
+
# your code for GET /other
|
551
|
+
end
|
552
|
+
end
|
553
|
+
|
554
|
+
class V2 < Grape::API
|
555
|
+
version 'v2', 'v3'
|
556
|
+
|
557
|
+
get '/var' do
|
558
|
+
# your code for GET /var
|
559
|
+
end
|
560
|
+
end
|
561
|
+
|
562
|
+
class V3 < Grape::API
|
563
|
+
version 'v3'
|
564
|
+
|
565
|
+
get '/foo' do
|
566
|
+
# your new code for GET /foo
|
567
|
+
end
|
568
|
+
end
|
569
|
+
```
|
570
|
+
|
571
|
+
Using the example provided, the subsequent endpoints will be accessible across various versions:
|
560
572
|
|
561
|
-
|
573
|
+
```shell
|
574
|
+
GET /v1/foo
|
575
|
+
GET /v1/other
|
576
|
+
GET /v2/foo # => Same behavior as v1
|
577
|
+
GET /v2/other # => Same behavior as v1
|
578
|
+
GET /v2/var # => New endpoint not available in v1
|
579
|
+
GET /v3/foo # => Different behavior to v1 and v2
|
580
|
+
GET /v3/other # => Same behavior as v1 and v2
|
581
|
+
GET /v3/var # => Same behavior as v2
|
582
|
+
```
|
583
|
+
|
584
|
+
There are four strategies in which clients can reach your API's endpoints: `:path`, `:header`, `:accept_version_header` and `:param`. The default strategy is `:path`.
|
585
|
+
|
586
|
+
### Strategies
|
587
|
+
|
588
|
+
#### Path
|
562
589
|
|
563
590
|
```ruby
|
564
591
|
version 'v1', using: :path
|
@@ -568,7 +595,7 @@ Using this versioning strategy, clients should pass the desired version in the U
|
|
568
595
|
|
569
596
|
curl http://localhost:9292/v1/statuses/public_timeline
|
570
597
|
|
571
|
-
|
598
|
+
#### Header
|
572
599
|
|
573
600
|
```ruby
|
574
601
|
version 'v1', using: :header, vendor: 'twitter'
|
@@ -586,20 +613,15 @@ Using this versioning strategy, clients should pass the desired version in the H
|
|
586
613
|
|
587
614
|
curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline
|
588
615
|
|
589
|
-
By default, the first matching version is used when no `Accept` header is
|
590
|
-
supplied. This behavior is similar to routing in Rails. To circumvent this default behavior,
|
591
|
-
one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error
|
592
|
-
is returned when no correct `Accept` header is supplied.
|
616
|
+
By default, the first matching version is used when no `Accept` header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error is returned when no correct `Accept` header is supplied.
|
593
617
|
|
594
|
-
When an invalid `Accept` header is supplied, a `406 Not Acceptable` error is returned if the `:cascade`
|
595
|
-
option is set to `false`. Otherwise a `404 Not Found` error is returned by Rack if no other route
|
596
|
-
matches.
|
618
|
+
When an invalid `Accept` header is supplied, a `406 Not Acceptable` error is returned if the `:cascade` option is set to `false`. Otherwise a `404 Not Found` error is returned by Rack if no other route matches.
|
597
619
|
|
598
620
|
Grape will evaluate the relative quality preference included in Accept headers and default to a quality of 1.0 when omitted. In the following example a Grape API that supports XML and JSON in that order will return JSON:
|
599
621
|
|
600
622
|
curl -H "Accept: text/xml;q=0.8, application/json;q=0.9" localhost:1234/resource
|
601
623
|
|
602
|
-
|
624
|
+
#### Accept-Version Header
|
603
625
|
|
604
626
|
```ruby
|
605
627
|
version 'v1', using: :accept_version_header
|
@@ -609,20 +631,15 @@ Using this versioning strategy, clients should pass the desired version in the H
|
|
609
631
|
|
610
632
|
curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline
|
611
633
|
|
612
|
-
By default, the first matching version is used when no `Accept-Version` header is
|
613
|
-
supplied. This behavior is similar to routing in Rails. To circumvent this default behavior,
|
614
|
-
one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error
|
615
|
-
is returned when no correct `Accept` header is supplied and the `:cascade` option is set to `false`.
|
616
|
-
Otherwise a `404 Not Found` error is returned by Rack if no other route matches.
|
634
|
+
By default, the first matching version is used when no `Accept-Version` header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error is returned when no correct `Accept` header is supplied and the `:cascade` option is set to `false`. Otherwise a `404 Not Found` error is returned by Rack if no other route matches.
|
617
635
|
|
618
|
-
|
636
|
+
#### Param
|
619
637
|
|
620
638
|
```ruby
|
621
639
|
version 'v1', using: :param
|
622
640
|
```
|
623
641
|
|
624
|
-
Using this versioning strategy, clients should pass the desired version as a request parameter,
|
625
|
-
either in the URL query string or in the request body.
|
642
|
+
Using this versioning strategy, clients should pass the desired version as a request parameter, either in the URL query string or in the request body.
|
626
643
|
|
627
644
|
curl http://localhost:9292/statuses/public_timeline?apiver=v1
|
628
645
|
|
@@ -713,13 +730,11 @@ API.configure do |config|
|
|
713
730
|
end
|
714
731
|
```
|
715
732
|
|
716
|
-
This will be available inside the API with `configuration`, as if it were
|
717
|
-
[mount configuration](#mount-configuration).
|
733
|
+
This will be available inside the API with `configuration`, as if it were [mount configuration](#mount-configuration).
|
718
734
|
|
719
735
|
## Parameters
|
720
736
|
|
721
|
-
Request parameters are available through the `params` hash object. This includes `GET`, `POST`
|
722
|
-
and `PUT` parameters, along with any named parameters you specify in your route strings.
|
737
|
+
Request parameters are available through the `params` hash object. This includes `GET`, `POST` and `PUT` parameters, along with any named parameters you specify in your route strings.
|
723
738
|
|
724
739
|
```ruby
|
725
740
|
get :public_timeline do
|
@@ -727,8 +742,7 @@ get :public_timeline do
|
|
727
742
|
end
|
728
743
|
```
|
729
744
|
|
730
|
-
Parameters are automatically populated from the request body on `POST` and `PUT` for form input, JSON and
|
731
|
-
XML content-types.
|
745
|
+
Parameters are automatically populated from the request body on `POST` and `PUT` for form input, JSON and XML content-types.
|
732
746
|
|
733
747
|
The request:
|
734
748
|
|
@@ -1067,8 +1081,7 @@ curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d
|
|
1067
1081
|
}
|
1068
1082
|
````
|
1069
1083
|
|
1070
|
-
Note that an attribute with a `nil` value is not considered *missing* and will also be returned
|
1071
|
-
when `include_missing` is set to `false`:
|
1084
|
+
Note that an attribute with a `nil` value is not considered *missing* and will also be returned when `include_missing` is set to `false`:
|
1072
1085
|
|
1073
1086
|
**Request**
|
1074
1087
|
|
@@ -1186,6 +1199,35 @@ curl -X POST -H "Content-Type: application/json" localhost:9292/child -d '{"chil
|
|
1186
1199
|
}
|
1187
1200
|
````
|
1188
1201
|
|
1202
|
+
### Parameter Precedence
|
1203
|
+
|
1204
|
+
Using `route_param` takes higher precedence over a regular parameter defined with same name:
|
1205
|
+
|
1206
|
+
```ruby
|
1207
|
+
params do
|
1208
|
+
requires :foo, type: String
|
1209
|
+
end
|
1210
|
+
route_param :foo do
|
1211
|
+
get do
|
1212
|
+
{ value: params[:foo] }
|
1213
|
+
end
|
1214
|
+
end
|
1215
|
+
```
|
1216
|
+
|
1217
|
+
**Request**
|
1218
|
+
|
1219
|
+
```bash
|
1220
|
+
curl -X POST -H "Content-Type: application/json" localhost:9292/bar -d '{"foo": "baz"}'
|
1221
|
+
```
|
1222
|
+
|
1223
|
+
**Response**
|
1224
|
+
|
1225
|
+
```json
|
1226
|
+
{
|
1227
|
+
"value": "bar"
|
1228
|
+
}
|
1229
|
+
```
|
1230
|
+
|
1189
1231
|
## Parameter Validation and Coercion
|
1190
1232
|
|
1191
1233
|
You can define validations and coercion options for your parameters using a `params` block.
|
@@ -1207,8 +1249,7 @@ put ':id' do
|
|
1207
1249
|
end
|
1208
1250
|
```
|
1209
1251
|
|
1210
|
-
When a type is specified an implicit validation is done after the coercion to ensure
|
1211
|
-
the output type is the one declared.
|
1252
|
+
When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.
|
1212
1253
|
|
1213
1254
|
Optional parameters can have a default value.
|
1214
1255
|
|
@@ -1220,9 +1261,7 @@ params do
|
|
1220
1261
|
end
|
1221
1262
|
```
|
1222
1263
|
|
1223
|
-
Default values are eagerly evaluated. Above `:non_random_number` will evaluate to the same
|
1224
|
-
number for each call to the endpoint of this `params` block. To have the default evaluate
|
1225
|
-
lazily with each request use a lambda, like `:random_number` above.
|
1264
|
+
Default values are eagerly evaluated. Above `:non_random_number` will evaluate to the same number for each call to the endpoint of this `params` block. To have the default evaluate lazily with each request use a lambda, like `:random_number` above.
|
1226
1265
|
|
1227
1266
|
Note that default values will be passed through to any validation options specified.
|
1228
1267
|
The following example will always fail if `:color` is not explicitly provided.
|
@@ -1241,6 +1280,15 @@ params do
|
|
1241
1280
|
end
|
1242
1281
|
```
|
1243
1282
|
|
1283
|
+
You can use the value of one parameter as the default value of some other parameter. In this case, if the `primary_color` parameter is not provided, it will have the same value as the `color` one. If both of them not provided, both of them will have `blue` value.
|
1284
|
+
|
1285
|
+
```ruby
|
1286
|
+
params do
|
1287
|
+
optional :color, type: String, default: 'blue'
|
1288
|
+
optional :primary_color, type: String, default: -> (params) { params[:color] }
|
1289
|
+
end
|
1290
|
+
```
|
1291
|
+
|
1244
1292
|
### Supported Parameter Types
|
1245
1293
|
|
1246
1294
|
The following are all valid types, supported out of the box by Grape:
|
@@ -1282,12 +1330,7 @@ get '/int' integers: { int: '45' }
|
|
1282
1330
|
|
1283
1331
|
### Custom Types and Coercions
|
1284
1332
|
|
1285
|
-
Aside from the default set of supported types listed above, any class can be
|
1286
|
-
used as a type as long as an explicit coercion method is supplied. If the type
|
1287
|
-
implements a class-level `parse` method, Grape will use it automatically.
|
1288
|
-
This method must take one string argument and return an instance of the correct
|
1289
|
-
type, or return an instance of `Grape::Types::InvalidValue` which optionally
|
1290
|
-
accepts a message to be returned in the response.
|
1333
|
+
Aside from the default set of supported types listed above, any class can be used as a type as long as an explicit coercion method is supplied. If the type implements a class-level `parse` method, Grape will use it automatically. This method must take one string argument and return an instance of the correct type, or return an instance of `Grape::Types::InvalidValue` which optionally accepts a message to be returned in the response.
|
1291
1334
|
|
1292
1335
|
```ruby
|
1293
1336
|
class Color
|
@@ -1297,7 +1340,7 @@ class Color
|
|
1297
1340
|
end
|
1298
1341
|
|
1299
1342
|
def self.parse(value)
|
1300
|
-
return new(value) if %w[blue red green]
|
1343
|
+
return new(value) if %w[blue red green].include?(value)
|
1301
1344
|
|
1302
1345
|
Grape::Types::InvalidValue.new('Unsupported color')
|
1303
1346
|
end
|
@@ -1315,10 +1358,7 @@ get '/stuff' do
|
|
1315
1358
|
end
|
1316
1359
|
```
|
1317
1360
|
|
1318
|
-
Alternatively, a custom coercion method may be supplied for any type of parameter
|
1319
|
-
using `coerce_with`. Any class or object may be given that implements a `parse` or
|
1320
|
-
`call` method, in that order of precedence. The method must accept a single string
|
1321
|
-
parameter, and the return value must match the given `type`.
|
1361
|
+
Alternatively, a custom coercion method may be supplied for any type of parameter using `coerce_with`. Any class or object may be given that implements a `parse` or `call` method, in that order of precedence. The method must accept a single string parameter, and the return value must match the given `type`.
|
1322
1362
|
|
1323
1363
|
```ruby
|
1324
1364
|
params do
|
@@ -1342,9 +1382,7 @@ params do
|
|
1342
1382
|
end
|
1343
1383
|
```
|
1344
1384
|
|
1345
|
-
Grape will assert that coerced values match the given `type`, and will reject the request
|
1346
|
-
if they do not. To override this behaviour, custom types may implement a `parsed?` method
|
1347
|
-
that should accept a single argument and return `true` if the value passes type validation.
|
1385
|
+
Grape will assert that coerced values match the given `type`, and will reject the request if they do not. To override this behaviour, custom types may implement a `parsed?` method that should accept a single argument and return `true` if the value passes type validation.
|
1348
1386
|
|
1349
1387
|
```ruby
|
1350
1388
|
class SecureUri
|
@@ -1379,9 +1417,7 @@ end
|
|
1379
1417
|
|
1380
1418
|
### First-Class `JSON` Types
|
1381
1419
|
|
1382
|
-
Grape supports complex parameters given as JSON-formatted strings using the special `type: JSON`
|
1383
|
-
declaration. JSON objects and arrays of objects are accepted equally, with nested validation
|
1384
|
-
rules applied to all objects in either case:
|
1420
|
+
Grape supports complex parameters given as JSON-formatted strings using the special `type: JSON` declaration. JSON objects and arrays of objects are accepted equally, with nested validation rules applied to all objects in either case:
|
1385
1421
|
|
1386
1422
|
```ruby
|
1387
1423
|
params do
|
@@ -1400,8 +1436,7 @@ client.get('/', json: '{"int":4}') # => HTTP 400
|
|
1400
1436
|
client.get('/', json: '[{"int":4}]') # => HTTP 400
|
1401
1437
|
```
|
1402
1438
|
|
1403
|
-
Additionally `type: Array[JSON]` may be used, which explicitly marks the parameter as an array
|
1404
|
-
of objects. If a single object is supplied it will be wrapped.
|
1439
|
+
Additionally `type: Array[JSON]` may be used, which explicitly marks the parameter as an array of objects. If a single object is supplied it will be wrapped.
|
1405
1440
|
|
1406
1441
|
```ruby
|
1407
1442
|
params do
|
@@ -1413,8 +1448,7 @@ get '/' do
|
|
1413
1448
|
params[:json].each { |obj| ... } # always works
|
1414
1449
|
end
|
1415
1450
|
```
|
1416
|
-
For stricter control over the type of JSON structure which may be supplied,
|
1417
|
-
use `type: Array, coerce_with: JSON` or `type: Hash, coerce_with: JSON`.
|
1451
|
+
For stricter control over the type of JSON structure which may be supplied, use `type: Array, coerce_with: JSON` or `type: Hash, coerce_with: JSON`.
|
1418
1452
|
|
1419
1453
|
### Multiple Allowed Types
|
1420
1454
|
|
@@ -1433,8 +1467,7 @@ client.get('/', status_code: 300) # => 300
|
|
1433
1467
|
client.get('/', status_code: %w(404 NOT FOUND)) # => [404, "NOT", "FOUND"]
|
1434
1468
|
```
|
1435
1469
|
|
1436
|
-
As a special case, variant-member-type collections may also be declared, by
|
1437
|
-
passing a `Set` or `Array` with more than one member to `type`:
|
1470
|
+
As a special case, variant-member-type collections may also be declared, by passing a `Set` or `Array` with more than one member to `type`:
|
1438
1471
|
|
1439
1472
|
```ruby
|
1440
1473
|
params do
|
@@ -1450,11 +1483,8 @@ client.get('/', status_codes: %w(1 two)) # => [1, "two"]
|
|
1450
1483
|
### Validation of Nested Parameters
|
1451
1484
|
|
1452
1485
|
Parameters can be nested using `group` or by calling `requires` or `optional` with a block.
|
1453
|
-
In the [above example](#parameter-validation-and-coercion), this means `params[:media][:url]` is required along with `params[:id]`,
|
1454
|
-
and `
|
1455
|
-
With a block, `group`, `requires` and `optional` accept an additional option `type` which can
|
1456
|
-
be either `Array` or `Hash`, and defaults to `Array`. Depending on the value, the nested
|
1457
|
-
parameters will be treated either as values of a hash or as values of hashes in an array.
|
1486
|
+
In the [above example](#parameter-validation-and-coercion), this means `params[:media][:url]` is required along with `params[:id]`, and `params[:audio][:format]` is required only if `params[:audio]` is present.
|
1487
|
+
With a block, `group`, `requires` and `optional` accept an additional option `type` which can be either `Array` or `Hash`, and defaults to `Array`. Depending on the value, the nested parameters will be treated either as values of a hash or as values of hashes in an array.
|
1458
1488
|
|
1459
1489
|
```ruby
|
1460
1490
|
params do
|
@@ -1472,9 +1502,7 @@ end
|
|
1472
1502
|
|
1473
1503
|
### Dependent Parameters
|
1474
1504
|
|
1475
|
-
Suppose some of your parameters are only relevant if another parameter is given;
|
1476
|
-
Grape allows you to express this relationship through the `given` method in your
|
1477
|
-
parameters block, like so:
|
1505
|
+
Suppose some of your parameters are only relevant if another parameter is given; Grape allows you to express this relationship through the `given` method in your parameters block, like so:
|
1478
1506
|
|
1479
1507
|
```ruby
|
1480
1508
|
params do
|
@@ -1513,31 +1541,45 @@ Note: param in `given` should be the renamed one. In the example, it should be `
|
|
1513
1541
|
|
1514
1542
|
### Group Options
|
1515
1543
|
|
1516
|
-
Parameters options can be grouped. It can be useful if you want to extract
|
1517
|
-
|
1518
|
-
|
1544
|
+
Parameters options can be grouped. It can be useful if you want to extract common validation or types for several parameters.
|
1545
|
+
Within these groups, individual parameters can extend or selectively override the common settings, allowing you to maintain the defaults at the group level while still applying parameter-specific rules where necessary.
|
1546
|
+
|
1547
|
+
The example below presents a typical case when parameters share common options.
|
1519
1548
|
|
1520
1549
|
```ruby
|
1521
1550
|
params do
|
1522
|
-
requires :first_name, type: String, regexp: /w+/, desc: 'First name'
|
1523
|
-
|
1524
|
-
requires :last_name, type: String, regexp: /w+/, desc: 'Last name'
|
1551
|
+
requires :first_name, type: String, regexp: /w+/, desc: 'First name', documentation: { in: 'body' }
|
1552
|
+
optional :middle_name, type: String, regexp: /w+/, desc: 'Middle name', documentation: { in: 'body', x: { nullable: true } }
|
1553
|
+
requires :last_name, type: String, regexp: /w+/, desc: 'Last name', documentation: { in: 'body' }
|
1525
1554
|
end
|
1526
1555
|
```
|
1527
1556
|
|
1528
|
-
Grape allows you to present the same logic through the `with` method in your
|
1529
|
-
parameters block, like so:
|
1557
|
+
Grape allows you to present the same logic through the `with` method in your parameters block, like so:
|
1530
1558
|
|
1531
1559
|
```ruby
|
1532
1560
|
params do
|
1533
|
-
with(type: String, regexp: /w
|
1561
|
+
with(type: String, regexp: /w+/, documentation: { in: 'body' }) do
|
1534
1562
|
requires :first_name, desc: 'First name'
|
1535
|
-
|
1563
|
+
optional :middle_name, desc: 'Middle name', documentation: { x: { nullable: true } }
|
1536
1564
|
requires :last_name, desc: 'Last name'
|
1537
1565
|
end
|
1538
1566
|
end
|
1539
1567
|
```
|
1540
1568
|
|
1569
|
+
You can organize settings into layers using nested `with' blocks. Each layer can use, add to, or change the settings of the layer above it. This helps to keep complex parameters organized and consistent, while still allowing for specific customizations to be made.
|
1570
|
+
|
1571
|
+
```ruby
|
1572
|
+
params do
|
1573
|
+
with(documentation: { in: 'body' }) do # Applies documentation to all nested parameters
|
1574
|
+
with(type: String, regexp: /\w+/) do # Applies type and validation to names
|
1575
|
+
requires :first_name, desc: 'First name'
|
1576
|
+
requires :last_name, desc: 'Last name'
|
1577
|
+
end
|
1578
|
+
optional :age, type: Integer, desc: 'Age', documentation: { x: { nullable: true } } # Specific settings for 'age'
|
1579
|
+
end
|
1580
|
+
end
|
1581
|
+
```
|
1582
|
+
|
1541
1583
|
### Renaming
|
1542
1584
|
|
1543
1585
|
You can rename parameters using `as`, which can be useful when refactoring existing APIs:
|
@@ -1560,13 +1602,9 @@ The value passed to `as` will be the key when calling `declared(params)`.
|
|
1560
1602
|
|
1561
1603
|
#### `allow_blank`
|
1562
1604
|
|
1563
|
-
Parameters can be defined as `allow_blank`, ensuring that they contain a value. By default, `requires`
|
1564
|
-
only validates that a parameter was sent in the request, regardless its value. With `allow_blank: false`,
|
1565
|
-
empty values or whitespace only values are invalid.
|
1605
|
+
Parameters can be defined as `allow_blank`, ensuring that they contain a value. By default, `requires` only validates that a parameter was sent in the request, regardless its value. With `allow_blank: false`, empty values or whitespace only values are invalid.
|
1566
1606
|
|
1567
|
-
`allow_blank` can be combined with both `requires` and `optional`. If the parameter is required, it has to contain
|
1568
|
-
a value. If it's optional, it's possible to not send it in the request, but if it's being sent, it has to have
|
1569
|
-
some value, and not an empty string/only whitespaces.
|
1607
|
+
`allow_blank` can be combined with both `requires` and `optional`. If the parameter is required, it has to contain a value. If it's optional, it's possible to not send it in the request, but if it's being sent, it has to have some value, and not an empty string/only whitespaces.
|
1570
1608
|
|
1571
1609
|
|
1572
1610
|
```ruby
|
@@ -1617,11 +1655,9 @@ end
|
|
1617
1655
|
```
|
1618
1656
|
|
1619
1657
|
The `:values` option can also be supplied with a `Proc`, evaluated lazily with each request.
|
1620
|
-
If the Proc has arity zero (i.e. it takes no arguments) it is expected to return either a list
|
1621
|
-
or a range which will then be used to validate the parameter.
|
1658
|
+
If the Proc has arity zero (i.e. it takes no arguments) it is expected to return either a list or a range which will then be used to validate the parameter.
|
1622
1659
|
|
1623
|
-
For example, given a status model you may want to restrict by hashtags that you have
|
1624
|
-
previously defined in the `HashTag` model.
|
1660
|
+
For example, given a status model you may want to restrict by hashtags that you have previously defined in the `HashTag` model.
|
1625
1661
|
|
1626
1662
|
```ruby
|
1627
1663
|
params do
|
@@ -1629,10 +1665,7 @@ params do
|
|
1629
1665
|
end
|
1630
1666
|
```
|
1631
1667
|
|
1632
|
-
Alternatively, a Proc with arity one (i.e. taking one argument) can be used to explicitly validate
|
1633
|
-
each parameter value. In that case, the Proc is expected to return a truthy value if the parameter
|
1634
|
-
value is valid. The parameter will be considered invalid if the Proc returns a falsy value or if it
|
1635
|
-
raises a StandardError.
|
1668
|
+
Alternatively, a Proc with arity one (i.e. taking one argument) can be used to explicitly validate each parameter value. In that case, the Proc is expected to return a truthy value if the parameter value is valid. The parameter will be considered invalid if the Proc returns a falsy value or if it raises a StandardError.
|
1636
1669
|
|
1637
1670
|
```ruby
|
1638
1671
|
params do
|
@@ -1654,9 +1687,7 @@ end
|
|
1654
1687
|
|
1655
1688
|
Parameters can be restricted from having a specific set of values with the `:except_values` option.
|
1656
1689
|
|
1657
|
-
The `except_values` validator behaves similarly to the `values` validator in that it accepts either
|
1658
|
-
an Array, a Range, or a Proc. Unlike the `values` validator, however, `except_values` only accepts
|
1659
|
-
Procs with arity zero.
|
1690
|
+
The `except_values` validator behaves similarly to the `values` validator in that it accepts either an Array, a Range, or a Proc. Unlike the `values` validator, however, `except_values` only accepts Procs with arity zero.
|
1660
1691
|
|
1661
1692
|
```ruby
|
1662
1693
|
params do
|
@@ -1677,11 +1708,24 @@ params do
|
|
1677
1708
|
end
|
1678
1709
|
```
|
1679
1710
|
|
1711
|
+
#### `length`
|
1712
|
+
|
1713
|
+
Parameters with types that support `#length` method can be restricted to have a specific length with the `:length` option.
|
1714
|
+
|
1715
|
+
The validator accepts `:min` or `:max` or both options or only `:is` to validate that the value of the parameter is within the given limits.
|
1716
|
+
|
1717
|
+
```ruby
|
1718
|
+
params do
|
1719
|
+
requires :code, type: String, length: { is: 2 }
|
1720
|
+
requires :str, type: String, length: { min: 3 }
|
1721
|
+
requires :list, type: [Integer], length: { min: 3, max: 5 }
|
1722
|
+
requires :hash, type: Hash, length: { max: 5 }
|
1723
|
+
end
|
1724
|
+
```
|
1725
|
+
|
1680
1726
|
#### `regexp`
|
1681
1727
|
|
1682
|
-
Parameters can be restricted to match a specific regular expression with the `:regexp` option. If the value
|
1683
|
-
does not match the regular expression an error will be returned. Note that this is true for both `requires`
|
1684
|
-
and `optional` parameters.
|
1728
|
+
Parameters can be restricted to match a specific regular expression with the `:regexp` option. If the value does not match the regular expression an error will be returned. Note that this is true for both `requires` and `optional` parameters.
|
1685
1729
|
|
1686
1730
|
```ruby
|
1687
1731
|
params do
|
@@ -1816,8 +1860,7 @@ namespace :statuses do
|
|
1816
1860
|
end
|
1817
1861
|
```
|
1818
1862
|
|
1819
|
-
The `namespace` method has a number of aliases, including: `group`, `resource`,
|
1820
|
-
`resources`, and `segment`. Use whichever reads the best for your API.
|
1863
|
+
The `namespace` method has a number of aliases, including: `group`, `resource`, `resources`, and `segment`. Use whichever reads the best for your API.
|
1821
1864
|
|
1822
1865
|
You can conveniently define a route parameter as a namespace using `route_param`.
|
1823
1866
|
|
@@ -1972,8 +2015,7 @@ end
|
|
1972
2015
|
|
1973
2016
|
### I18n
|
1974
2017
|
|
1975
|
-
Grape supports I18n for parameter-related error messages, but will fallback to English if
|
1976
|
-
translations for the default locale have not been provided. See [en.yml](lib/grape/locale/en.yml) for message keys.
|
2018
|
+
Grape supports I18n for parameter-related error messages, but will fallback to English if translations for the default locale have not been provided. See [en.yml](lib/grape/locale/en.yml) for message keys.
|
1977
2019
|
|
1978
2020
|
In case your app enforces available locales only and :en is not included in your available locales, Grape cannot fall back to English and will return the translation key for the error message. To avoid this behaviour, either provide a translation for your default locale or add :en to your available locales.
|
1979
2021
|
|
@@ -1998,6 +2040,16 @@ params do
|
|
1998
2040
|
end
|
1999
2041
|
```
|
2000
2042
|
|
2043
|
+
#### `length`
|
2044
|
+
|
2045
|
+
```ruby
|
2046
|
+
params do
|
2047
|
+
requires :code, type: String, length: { is: 2, message: 'code is expected to be exactly 2 characters long' }
|
2048
|
+
requires :str, type: String, length: { min: 5, message: 'str is expected to be atleast 5 characters long' }
|
2049
|
+
requires :list, type: [Integer], length: { min: 2, max: 3, message: 'list is expected to have between 2 and 3 elements' }
|
2050
|
+
end
|
2051
|
+
```
|
2052
|
+
|
2001
2053
|
#### `all_or_none_of`
|
2002
2054
|
|
2003
2055
|
```ruby
|
@@ -2106,6 +2158,40 @@ params do
|
|
2106
2158
|
end
|
2107
2159
|
```
|
2108
2160
|
|
2161
|
+
### Using `dry-validation` or `dry-schema`
|
2162
|
+
|
2163
|
+
As an alternative to the `params` DSL described above, you can use a schema or `dry-validation` contract to describe an endpoint's parameters. This can be especially useful if you use the above already in some other parts of your application. If not, you'll need to add `dry-validation` or `dry-schema` to your `Gemfile`.
|
2164
|
+
|
2165
|
+
Then call `contract` with a contract or schema defined previously:
|
2166
|
+
|
2167
|
+
```rb
|
2168
|
+
CreateOrdersSchema = Dry::Schema.Params do
|
2169
|
+
required(:orders).array(:hash) do
|
2170
|
+
required(:name).filled(:string)
|
2171
|
+
optional(:volume).maybe(:integer, lt?: 9)
|
2172
|
+
end
|
2173
|
+
end
|
2174
|
+
|
2175
|
+
# ...
|
2176
|
+
|
2177
|
+
contract CreateOrdersSchema
|
2178
|
+
```
|
2179
|
+
|
2180
|
+
or with a block, using the [schema definition syntax](https://dry-rb.org/gems/dry-schema/1.13/#quick-start):
|
2181
|
+
|
2182
|
+
```rb
|
2183
|
+
contract do
|
2184
|
+
required(:orders).array(:hash) do
|
2185
|
+
required(:name).filled(:string)
|
2186
|
+
optional(:volume).maybe(:integer, lt?: 9)
|
2187
|
+
end
|
2188
|
+
end
|
2189
|
+
```
|
2190
|
+
|
2191
|
+
The latter will define a coercing schema (`Dry::Schema.Params`). When using the former approach, it's up to you to decide whether the input will need coercing.
|
2192
|
+
|
2193
|
+
The `params` and `contract` declarations can also be used together in the same API, e.g. to describe different parts of a nested namespace for an endpoint.
|
2194
|
+
|
2109
2195
|
## Headers
|
2110
2196
|
|
2111
2197
|
### Request
|
@@ -2205,8 +2291,7 @@ namespace ':id' do
|
|
2205
2291
|
end
|
2206
2292
|
```
|
2207
2293
|
|
2208
|
-
Optionally, you can define requirements for your named route parameters using regular
|
2209
|
-
expressions on namespace or endpoint. The route will match only if all requirements are met.
|
2294
|
+
Optionally, you can define requirements for your named route parameters using regular expressions on namespace or endpoint. The route will match only if all requirements are met.
|
2210
2295
|
|
2211
2296
|
```ruby
|
2212
2297
|
get ':id', requirements: { id: /[0-9]*/ } do
|
@@ -2224,8 +2309,7 @@ end
|
|
2224
2309
|
|
2225
2310
|
## Helpers
|
2226
2311
|
|
2227
|
-
You can define helper methods that your endpoints can use with the `helpers`
|
2228
|
-
macro by either giving a block or an array of modules.
|
2312
|
+
You can define helper methods that your endpoints can use with the `helpers` macro by either giving a block or an array of modules.
|
2229
2313
|
|
2230
2314
|
```ruby
|
2231
2315
|
module StatusHelpers
|
@@ -2464,11 +2548,36 @@ end
|
|
2464
2548
|
API.recognize_path '/statuses'
|
2465
2549
|
```
|
2466
2550
|
|
2551
|
+
Since version `2.1.0`, the `recognize_path` method takes into account the parameters type to determine which endpoint should match with given path.
|
2552
|
+
|
2553
|
+
```ruby
|
2554
|
+
class Books < Grape::API
|
2555
|
+
resource :books do
|
2556
|
+
route_param :id, type: Integer do
|
2557
|
+
# GET /books/:id
|
2558
|
+
get do
|
2559
|
+
#...
|
2560
|
+
end
|
2561
|
+
end
|
2562
|
+
|
2563
|
+
resource :share do
|
2564
|
+
# POST /books/share
|
2565
|
+
post do
|
2566
|
+
# ....
|
2567
|
+
end
|
2568
|
+
end
|
2569
|
+
end
|
2570
|
+
end
|
2571
|
+
|
2572
|
+
API.recognize_path '/books/1' # => /books/:id
|
2573
|
+
API.recognize_path '/books/share' # => /books/share
|
2574
|
+
API.recognize_path '/books/other' # => nil
|
2575
|
+
```
|
2576
|
+
|
2577
|
+
|
2467
2578
|
## Allowed Methods
|
2468
2579
|
|
2469
|
-
When you add a `GET` route for a resource, a route for the `HEAD`
|
2470
|
-
method will also be added automatically. You can disable this
|
2471
|
-
behavior with `do_not_route_head!`.
|
2580
|
+
When you add a `GET` route for a resource, a route for the `HEAD` method will also be added automatically. You can disable this behavior with `do_not_route_head!`.
|
2472
2581
|
|
2473
2582
|
``` ruby
|
2474
2583
|
class API < Grape::API
|
@@ -2480,11 +2589,7 @@ class API < Grape::API
|
|
2480
2589
|
end
|
2481
2590
|
```
|
2482
2591
|
|
2483
|
-
When you add a route for a resource, a route for the `OPTIONS`
|
2484
|
-
method will also be added. The response to an OPTIONS request will
|
2485
|
-
include an "Allow" header listing the supported methods. If the resource
|
2486
|
-
has `before` and `after` callbacks they will be executed, but no other callbacks will
|
2487
|
-
run.
|
2592
|
+
When you add a route for a resource, a route for the `OPTIONS` method will also be added. The response to an OPTIONS request will include an "Allow" header listing the supported methods. If the resource has `before` and `after` callbacks they will be executed, but no other callbacks will run.
|
2488
2593
|
|
2489
2594
|
```ruby
|
2490
2595
|
class API < Grape::API
|
@@ -2513,10 +2618,7 @@ curl -v -X OPTIONS http://localhost:3000/rt_count
|
|
2513
2618
|
|
2514
2619
|
You can disable this behavior with `do_not_route_options!`.
|
2515
2620
|
|
2516
|
-
If a request for a resource is made with an unsupported HTTP method, an
|
2517
|
-
HTTP 405 (Method Not Allowed) response will be returned. If the resource
|
2518
|
-
has `before` callbacks they will be executed, but no other callbacks will
|
2519
|
-
run.
|
2621
|
+
If a request for a resource is made with an unsupported HTTP method, an HTTP 405 (Method Not Allowed) response will be returned. If the resource has `before` callbacks they will be executed, but no other callbacks will run.
|
2520
2622
|
|
2521
2623
|
``` shell
|
2522
2624
|
curl -X DELETE -v http://localhost:3000/rt_count/
|
@@ -2542,8 +2644,7 @@ Anything that responds to `#to_s` can be given as a first argument to `error!`.
|
|
2542
2644
|
error! :not_found, 404
|
2543
2645
|
```
|
2544
2646
|
|
2545
|
-
You can also return JSON formatted objects by raising error! and passing a hash
|
2546
|
-
instead of a message.
|
2647
|
+
You can also return JSON formatted objects by raising error! and passing a hash instead of a message.
|
2547
2648
|
|
2548
2649
|
```ruby
|
2549
2650
|
error!({ error: 'unexpected error', detail: 'missing widget' }, 500)
|
@@ -2608,8 +2709,7 @@ route :any, '*path' do
|
|
2608
2709
|
end
|
2609
2710
|
```
|
2610
2711
|
|
2611
|
-
It is very crucial to __define this endpoint at the very end of your API__, as it
|
2612
|
-
literally accepts every request.
|
2712
|
+
It is very crucial to __define this endpoint at the very end of your API__, as it literally accepts every request.
|
2613
2713
|
|
2614
2714
|
## Exception Handling
|
2615
2715
|
|
@@ -2851,33 +2951,11 @@ Any exception that is not subclass of `StandardError` should be rescued explicit
|
|
2851
2951
|
Usually it is not a case for an application logic as such errors point to problems in Ruby runtime.
|
2852
2952
|
This is following [standard recommendations for exceptions handling](https://ruby-doc.org/core/Exception.html).
|
2853
2953
|
|
2854
|
-
### Rails 3.x
|
2855
|
-
|
2856
|
-
When mounted inside containers, such as Rails 3.x, errors such as "404 Not Found" or
|
2857
|
-
"406 Not Acceptable" will likely be handled and rendered by Rails handlers. For instance,
|
2858
|
-
accessing a nonexistent route "/api/foo" raises a 404, which inside rails will ultimately
|
2859
|
-
be translated to an `ActionController::RoutingError`, which most likely will get rendered
|
2860
|
-
to a HTML error page.
|
2861
|
-
|
2862
|
-
Most APIs will enjoy preventing downstream handlers from handling errors. You may set the
|
2863
|
-
`:cascade` option to `false` for the entire API or separately on specific `version` definitions,
|
2864
|
-
which will remove the `X-Cascade: true` header from API responses.
|
2865
|
-
|
2866
|
-
```ruby
|
2867
|
-
cascade false
|
2868
|
-
```
|
2869
|
-
|
2870
|
-
```ruby
|
2871
|
-
version 'v1', using: :header, vendor: 'twitter', cascade: false
|
2872
|
-
```
|
2873
|
-
|
2874
2954
|
## Logging
|
2875
2955
|
|
2876
|
-
`Grape::API` provides a `logger` method which by default will return an instance of the `Logger`
|
2877
|
-
class from Ruby's standard library.
|
2956
|
+
`Grape::API` provides a `logger` method which by default will return an instance of the `Logger` class from Ruby's standard library.
|
2878
2957
|
|
2879
|
-
To log messages from within an endpoint, you need to define a helper to make the logger
|
2880
|
-
available in the endpoint context.
|
2958
|
+
To log messages from within an endpoint, you need to define a helper to make the logger available in the endpoint context.
|
2881
2959
|
|
2882
2960
|
```ruby
|
2883
2961
|
class API < Grape::API
|
@@ -2926,9 +3004,7 @@ For similar to Rails request logging try the [grape_logging](https://github.com/
|
|
2926
3004
|
|
2927
3005
|
## API Formats
|
2928
3006
|
|
2929
|
-
Your API can declare which content-types to support by using `content_type`. If you do not specify any, Grape will support
|
2930
|
-
_XML_, _JSON_, _BINARY_, and _TXT_ content-types. The default format is `:txt`; you can change this with `default_format`.
|
2931
|
-
Essentially, the two APIs below are equivalent.
|
3007
|
+
Your API can declare which content-types to support by using `content_type`. If you do not specify any, Grape will support _XML_, _JSON_, _BINARY_, and _TXT_ content-types. The default format is `:txt`; you can change this with `default_format`. Essentially, the two APIs below are equivalent.
|
2932
3008
|
|
2933
3009
|
```ruby
|
2934
3010
|
class Twitter::API < Grape::API
|
@@ -2947,9 +3023,7 @@ class Twitter::API < Grape::API
|
|
2947
3023
|
end
|
2948
3024
|
```
|
2949
3025
|
|
2950
|
-
If you declare any `content_type` whatsoever, the Grape defaults will be overridden. For example, the following API will only
|
2951
|
-
support the `:xml` and `:rss` content-types, but not `:txt`, `:json`, or `:binary`. Importantly, this means the `:txt`
|
2952
|
-
default format is not supported! So, make sure to set a new `default_format`.
|
3026
|
+
If you declare any `content_type` whatsoever, the Grape defaults will be overridden. For example, the following API will only support the `:xml` and `:rss` content-types, but not `:txt`, `:json`, or `:binary`. Importantly, this means the `:txt` default format is not supported! So, make sure to set a new `default_format`.
|
2953
3027
|
|
2954
3028
|
```ruby
|
2955
3029
|
class Twitter::API < Grape::API
|
@@ -2960,8 +3034,7 @@ class Twitter::API < Grape::API
|
|
2960
3034
|
end
|
2961
3035
|
```
|
2962
3036
|
|
2963
|
-
Serialization takes place automatically. For example, you do not have to call `to_json` in each JSON API endpoint
|
2964
|
-
implementation. The response format (and thus the automatic serialization) is determined in the following order:
|
3037
|
+
Serialization takes place automatically. For example, you do not have to call `to_json` in each JSON API endpoint implementation. The response format (and thus the automatic serialization) is determined in the following order:
|
2965
3038
|
* Use the file extension, if specified. If the file is .json, choose the JSON format.
|
2966
3039
|
* Use the value of the `format` parameter in the query string, if specified.
|
2967
3040
|
* Use the format set by the `format` option, if specified.
|
@@ -2984,18 +3057,13 @@ class MultipleFormatAPI < Grape::API
|
|
2984
3057
|
end
|
2985
3058
|
```
|
2986
3059
|
|
2987
|
-
* `GET /hello` (with an `Accept: */*` header) does not have an extension or a `format` parameter, so it will respond with
|
2988
|
-
JSON (the default format).
|
3060
|
+
* `GET /hello` (with an `Accept: */*` header) does not have an extension or a `format` parameter, so it will respond with JSON (the default format).
|
2989
3061
|
* `GET /hello.xml` has a recognized extension, so it will respond with XML.
|
2990
3062
|
* `GET /hello?format=xml` has a recognized `format` parameter, so it will respond with XML.
|
2991
|
-
* `GET /hello.xml?format=json` has a recognized extension (which takes precedence over the `format` parameter), so it will
|
2992
|
-
|
2993
|
-
* `GET /hello.xls`
|
2994
|
-
|
2995
|
-
* `GET /hello.xls` with an `Accept: application/xml` header has an unrecognized extension, but the `Accept` header
|
2996
|
-
corresponds to a recognized format, so it will respond with XML.
|
2997
|
-
* `GET /hello.xls` with an `Accept: text/plain` header has an unrecognized extension *and* an unrecognized `Accept` header,
|
2998
|
-
so it will respond with JSON (the default format).
|
3063
|
+
* `GET /hello.xml?format=json` has a recognized extension (which takes precedence over the `format` parameter), so it will respond with XML.
|
3064
|
+
* `GET /hello.xls` (with an `Accept: */*` header) has an extension, but that extension is not recognized, so it will respond with JSON (the default format).
|
3065
|
+
* `GET /hello.xls` with an `Accept: application/xml` header has an unrecognized extension, but the `Accept` header corresponds to a recognized format, so it will respond with XML.
|
3066
|
+
* `GET /hello.xls` with an `Accept: text/plain` header has an unrecognized extension *and* an unrecognized `Accept` header, so it will respond with JSON (the default format).
|
2999
3067
|
|
3000
3068
|
You can override this process explicitly by specifying `env['api.format']` in the API itself.
|
3001
3069
|
For example, the following API will let you upload arbitrary files and return their contents as an attachment with the correct MIME type.
|
@@ -3012,8 +3080,7 @@ class Twitter::API < Grape::API
|
|
3012
3080
|
end
|
3013
3081
|
```
|
3014
3082
|
|
3015
|
-
You can have your API only respond to a single format with `format`. If you use this, the API will **not** respond to file
|
3016
|
-
extensions other than specified in `format`. For example, consider the following API.
|
3083
|
+
You can have your API only respond to a single format with `format`. If you use this, the API will **not** respond to file extensions other than specified in `format`. For example, consider the following API.
|
3017
3084
|
|
3018
3085
|
```ruby
|
3019
3086
|
class SingleFormatAPI < Grape::API
|
@@ -3028,14 +3095,10 @@ end
|
|
3028
3095
|
* `GET /hello` will respond with JSON.
|
3029
3096
|
* `GET /hello.json` will respond with JSON.
|
3030
3097
|
* `GET /hello.xml`, `GET /hello.foobar`, or *any* other extension will respond with an HTTP 404 error code.
|
3031
|
-
* `GET /hello?format=xml` will respond with an HTTP 406 error code, because the XML format specified by the request parameter
|
3032
|
-
|
3033
|
-
* `GET /hello` with an `Accept: application/xml` header will still respond with JSON, since it could not negotiate a
|
3034
|
-
recognized content-type from the headers and JSON is the effective default.
|
3098
|
+
* `GET /hello?format=xml` will respond with an HTTP 406 error code, because the XML format specified by the request parameter is not supported.
|
3099
|
+
* `GET /hello` with an `Accept: application/xml` header will still respond with JSON, since it could not negotiate a recognized content-type from the headers and JSON is the effective default.
|
3035
3100
|
|
3036
|
-
The formats apply to parsing, too. The following API will only respond to the JSON content-type and will not parse any other
|
3037
|
-
input than `application/json`, `application/x-www-form-urlencoded`, `multipart/form-data`, `multipart/related` and
|
3038
|
-
`multipart/mixed`. All other requests will fail with an HTTP 406 error code.
|
3101
|
+
The formats apply to parsing, too. The following API will only respond to the JSON content-type and will not parse any other input than `application/json`, `application/x-www-form-urlencoded`, `multipart/form-data`, `multipart/related` and `multipart/mixed`. All other requests will fail with an HTTP 406 error code.
|
3039
3102
|
|
3040
3103
|
```ruby
|
3041
3104
|
class Twitter::API < Grape::API
|
@@ -3091,23 +3154,18 @@ end
|
|
3091
3154
|
Built-in formatters are the following.
|
3092
3155
|
|
3093
3156
|
* `:json`: use object's `to_json` when available, otherwise call `MultiJson.dump`
|
3094
|
-
* `:xml`: use object's `to_xml` when available, usually via `MultiXml
|
3157
|
+
* `:xml`: use object's `to_xml` when available, usually via `MultiXml`
|
3095
3158
|
* `:txt`: use object's `to_txt` when available, otherwise `to_s`
|
3096
3159
|
* `:serializable_hash`: use object's `serializable_hash` when available, otherwise fallback to `:json`
|
3097
3160
|
* `:binary`: data will be returned "as is"
|
3098
3161
|
|
3099
|
-
If a body is present in a request to an API, with a Content-Type header value that is of an unsupported type a
|
3100
|
-
"415 Unsupported Media Type" error code will be returned by Grape.
|
3162
|
+
If a body is present in a request to an API, with a Content-Type header value that is of an unsupported type a "415 Unsupported Media Type" error code will be returned by Grape.
|
3101
3163
|
|
3102
|
-
Response statuses that indicate no content as defined by [Rack](https://github.com/rack)
|
3103
|
-
[here](https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L567)
|
3104
|
-
will bypass serialization and the body entity - though there should be none -
|
3105
|
-
will not be modified.
|
3164
|
+
Response statuses that indicate no content as defined by [Rack](https://github.com/rack) [here](https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L567) will bypass serialization and the body entity - though there should be none - will not be modified.
|
3106
3165
|
|
3107
3166
|
### JSONP
|
3108
3167
|
|
3109
|
-
Grape supports JSONP via [Rack::JSONP](https://github.com/rack/rack-contrib), part of the
|
3110
|
-
[rack-contrib](https://github.com/rack/rack-contrib) gem. Add `rack-contrib` to your `Gemfile`.
|
3168
|
+
Grape supports JSONP via [Rack::JSONP](https://github.com/rack/rack-contrib), part of the [rack-contrib](https://github.com/rack/rack-contrib) gem. Add `rack-contrib` to your `Gemfile`.
|
3111
3169
|
|
3112
3170
|
```ruby
|
3113
3171
|
require 'rack/contrib'
|
@@ -3123,9 +3181,7 @@ end
|
|
3123
3181
|
|
3124
3182
|
### CORS
|
3125
3183
|
|
3126
|
-
Grape supports CORS via [Rack::CORS](https://github.com/cyu/rack-cors), part of the
|
3127
|
-
[rack-cors](https://github.com/cyu/rack-cors) gem. Add `rack-cors` to your `Gemfile`,
|
3128
|
-
then use the middleware in your config.ru file.
|
3184
|
+
Grape supports CORS via [Rack::CORS](https://github.com/cyu/rack-cors), part of the [rack-cors](https://github.com/cyu/rack-cors) gem. Add `rack-cors` to your `Gemfile`, then use the middleware in your config.ru file.
|
3129
3185
|
|
3130
3186
|
```ruby
|
3131
3187
|
require 'rack/cors'
|
@@ -3143,8 +3199,7 @@ run Twitter::API
|
|
3143
3199
|
|
3144
3200
|
## Content-type
|
3145
3201
|
|
3146
|
-
Content-type is set by the formatter. You can override the content-type of the response at runtime
|
3147
|
-
by setting the `Content-Type` header.
|
3202
|
+
Content-type is set by the formatter. You can override the content-type of the response at runtime by setting the `Content-Type` header.
|
3148
3203
|
|
3149
3204
|
```ruby
|
3150
3205
|
class API < Grape::API
|
@@ -3157,16 +3212,12 @@ end
|
|
3157
3212
|
|
3158
3213
|
## API Data Formats
|
3159
3214
|
|
3160
|
-
Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters
|
3161
|
-
section above. It also supports custom data formats. You must declare additional content-types via
|
3162
|
-
`content_type` and optionally supply a parser via `parser` unless a parser is already available within
|
3163
|
-
Grape to enable a custom format. Such a parser can be a function or a class.
|
3215
|
+
Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters section above. It also supports custom data formats. You must declare additional content-types via `content_type` and optionally supply a parser via `parser` unless a parser is already available within Grape to enable a custom format. Such a parser can be a function or a class.
|
3164
3216
|
|
3165
3217
|
With a parser, parsed data is available "as-is" in `env['api.request.body']`.
|
3166
3218
|
Without a parser, data is available "as-is" and in `env['api.request.input']`.
|
3167
3219
|
|
3168
|
-
The following example is a trivial parser that will assign any input with the "text/custom" content-type
|
3169
|
-
to `:value`. The parameter will be available via `params[:value]` inside the API call.
|
3220
|
+
The following example is a trivial parser that will assign any input with the "text/custom" content-type to `:value`. The parameter will be available via `params[:value]` inside the API call.
|
3170
3221
|
|
3171
3222
|
```ruby
|
3172
3223
|
module CustomParser
|
@@ -3200,9 +3251,7 @@ Grape uses `JSON` and `ActiveSupport::XmlMini` for JSON and XML parsing by defau
|
|
3200
3251
|
|
3201
3252
|
## RESTful Model Representations
|
3202
3253
|
|
3203
|
-
Grape supports a range of ways to present your data with some help from a generic `present` method,
|
3204
|
-
which accepts two arguments: the object to be presented and the options associated with it. The options
|
3205
|
-
hash may include `:with`, which defines the entity to expose.
|
3254
|
+
Grape supports a range of ways to present your data with some help from a generic `present` method, which accepts two arguments: the object to be presented and the options associated with it. The options hash may include `:with`, which defines the entity to expose.
|
3206
3255
|
|
3207
3256
|
### Grape Entities
|
3208
3257
|
|
@@ -3281,8 +3330,7 @@ The response will be
|
|
3281
3330
|
}
|
3282
3331
|
```
|
3283
3332
|
|
3284
|
-
In addition to separately organizing entities, it may be useful to put them as namespaced
|
3285
|
-
classes underneath the model they represent.
|
3333
|
+
In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.
|
3286
3334
|
|
3287
3335
|
```ruby
|
3288
3336
|
class Status
|
@@ -3296,11 +3344,7 @@ class Status
|
|
3296
3344
|
end
|
3297
3345
|
```
|
3298
3346
|
|
3299
|
-
If you organize your entities this way, Grape will automatically detect the `Entity` class and
|
3300
|
-
use it to present your models. In this example, if you added `present Status.new` to your endpoint,
|
3301
|
-
Grape will automatically detect that there is a `Status::Entity` class and use that as the
|
3302
|
-
representative entity. This can still be overridden by using the `:with` option or an explicit
|
3303
|
-
`represents` call.
|
3347
|
+
If you organize your entities this way, Grape will automatically detect the `Entity` class and use it to present your models. In this example, if you added `present Status.new` to your endpoint, Grape will automatically detect that there is a `Status::Entity` class and use that as the representative entity. This can still be overridden by using the `:with` option or an explicit `represents` call.
|
3304
3348
|
|
3305
3349
|
You can present `hash` with `Grape::Presenters::Presenter` to keep things consistent.
|
3306
3350
|
|
@@ -3333,15 +3377,11 @@ You can use [Roar](https://github.com/apotonick/roar) to render HAL or Collectio
|
|
3333
3377
|
|
3334
3378
|
### Rabl
|
3335
3379
|
|
3336
|
-
You can use [Rabl](https://github.com/nesquena/rabl) templates with the help of the
|
3337
|
-
[grape-rabl](https://github.com/ruby-grape/grape-rabl) gem, which defines a custom Grape Rabl
|
3338
|
-
formatter.
|
3380
|
+
You can use [Rabl](https://github.com/nesquena/rabl) templates with the help of the [grape-rabl](https://github.com/ruby-grape/grape-rabl) gem, which defines a custom Grape Rabl formatter.
|
3339
3381
|
|
3340
3382
|
### Active Model Serializers
|
3341
3383
|
|
3342
|
-
You can use [Active Model Serializers](https://github.com/rails-api/active_model_serializers) serializers with the help of the
|
3343
|
-
[grape-active_model_serializers](https://github.com/jrhe/grape-active_model_serializers) gem, which defines a custom Grape AMS
|
3344
|
-
formatter.
|
3384
|
+
You can use [Active Model Serializers](https://github.com/rails-api/active_model_serializers) serializers with the help of the [grape-active_model_serializers](https://github.com/jrhe/grape-active_model_serializers) gem, which defines a custom Grape AMS formatter.
|
3345
3385
|
|
3346
3386
|
## Sending Raw or No Data
|
3347
3387
|
|
@@ -3381,9 +3421,7 @@ class API < Grape::API
|
|
3381
3421
|
end
|
3382
3422
|
```
|
3383
3423
|
|
3384
|
-
You can also set the response to a file with `sendfile`. This works with the
|
3385
|
-
[Rack::Sendfile](https://www.rubydoc.info/gems/rack/Rack/Sendfile) middleware to optimally send
|
3386
|
-
the file through your web server software.
|
3424
|
+
You can also set the response to a file with `sendfile`. This works with the [Rack::Sendfile](https://www.rubydoc.info/gems/rack/Rack/Sendfile) middleware to optimally send the file through your web server software.
|
3387
3425
|
|
3388
3426
|
```ruby
|
3389
3427
|
class API < Grape::API
|
@@ -3427,9 +3465,7 @@ end
|
|
3427
3465
|
|
3428
3466
|
### Basic Auth
|
3429
3467
|
|
3430
|
-
Grape has built-in Basic authentication (the given `block`
|
3431
|
-
is executed in the context of the current `Endpoint`). Authentication
|
3432
|
-
applies to the current namespace and any children, but not parents.
|
3468
|
+
Grape has built-in Basic authentication (the given `block` is executed in the context of the current `Endpoint`). Authentication applies to the current namespace and any children, but not parents.
|
3433
3469
|
|
3434
3470
|
```ruby
|
3435
3471
|
http_basic do |username, password|
|
@@ -3440,16 +3476,13 @@ end
|
|
3440
3476
|
|
3441
3477
|
### Register custom middleware for authentication
|
3442
3478
|
|
3443
|
-
Grape can use custom Middleware for authentication. How to implement these
|
3444
|
-
Middleware have a look at `Rack::Auth::Basic` or similar implementations.
|
3445
|
-
|
3479
|
+
Grape can use custom Middleware for authentication. How to implement these Middleware have a look at `Rack::Auth::Basic` or similar implementations.
|
3446
3480
|
|
3447
3481
|
For registering a Middleware you need the following options:
|
3448
3482
|
|
3449
3483
|
* `label` - the name for your authenticator to use it later
|
3450
3484
|
* `MiddlewareClass` - the MiddlewareClass to use for authentication
|
3451
|
-
* `option_lookup_proc` - A Proc with one Argument to lookup the options at
|
3452
|
-
runtime (return value is an `Array` as Parameter for the Middleware).
|
3485
|
+
* `option_lookup_proc` - A Proc with one Argument to lookup the options at runtime (return value is an `Array` as Parameter for the Middleware).
|
3453
3486
|
|
3454
3487
|
Example:
|
3455
3488
|
|
@@ -3473,7 +3506,7 @@ You can access the controller params, headers, and helpers through the context w
|
|
3473
3506
|
|
3474
3507
|
Grape routes can be reflected at runtime. This can notably be useful for generating documentation.
|
3475
3508
|
|
3476
|
-
Grape exposes arrays of API versions and compiled routes. Each route contains a `
|
3509
|
+
Grape exposes arrays of API versions and compiled routes. Each route contains a `prefix`, `version`, `namespace`, `method` and `params`. You can add custom route settings to the route metadata with `route_setting`.
|
3477
3510
|
|
3478
3511
|
```ruby
|
3479
3512
|
class TwitterAPI < Grape::API
|
@@ -3496,7 +3529,7 @@ TwitterAPI::routes[0].description # => 'Includes custom settings.'
|
|
3496
3529
|
TwitterAPI::routes[0].settings[:custom] # => { key: 'value' }
|
3497
3530
|
```
|
3498
3531
|
|
3499
|
-
Note that `Route#route_xyz` methods have been deprecated since 0.15.0.
|
3532
|
+
Note that `Route#route_xyz` methods have been deprecated since 0.15.0 and removed since 2.0.1.
|
3500
3533
|
|
3501
3534
|
Please use `Route#xyz` instead.
|
3502
3535
|
|
@@ -3516,15 +3549,12 @@ class MyAPI < Grape::API
|
|
3516
3549
|
requires :id, type: Integer, desc: 'Identity.'
|
3517
3550
|
end
|
3518
3551
|
get 'params/:id' do
|
3519
|
-
route.
|
3552
|
+
route.params[params[:id]] # yields the parameter description
|
3520
3553
|
end
|
3521
3554
|
end
|
3522
3555
|
```
|
3523
3556
|
|
3524
|
-
The current endpoint responding to the request is `self` within the API block
|
3525
|
-
or `env['api.endpoint']` elsewhere. The endpoint has some interesting properties,
|
3526
|
-
such as `source` which gives you access to the original code block of the API
|
3527
|
-
implementation. This can be particularly useful for building a logger middleware.
|
3557
|
+
The current endpoint responding to the request is `self` within the API block or `env['api.endpoint']` elsewhere. The endpoint has some interesting properties, such as `source` which gives you access to the original code block of the API implementation. This can be particularly useful for building a logger middleware.
|
3528
3558
|
|
3529
3559
|
```ruby
|
3530
3560
|
class ApiLogger < Grape::Middleware::Base
|
@@ -3538,10 +3568,8 @@ end
|
|
3538
3568
|
|
3539
3569
|
## Before, After and Finally
|
3540
3570
|
|
3541
|
-
Blocks can be executed before or after every API call, using `before`, `after`,
|
3542
|
-
`
|
3543
|
-
If the API fails the `after` call will not be triggered, if you need code to execute for sure
|
3544
|
-
use the `finally`.
|
3571
|
+
Blocks can be executed before or after every API call, using `before`, `after`, `before_validation` and `after_validation`.
|
3572
|
+
If the API fails the `after` call will not be triggered, if you need code to execute for sure use the `finally`.
|
3545
3573
|
|
3546
3574
|
Before and after callbacks execute in the following order:
|
3547
3575
|
|
@@ -3555,13 +3583,9 @@ Before and after callbacks execute in the following order:
|
|
3555
3583
|
|
3556
3584
|
Steps 4, 5 and 6 only happen if validation succeeds.
|
3557
3585
|
|
3558
|
-
If a request for a resource is made with an unsupported HTTP method (returning
|
3559
|
-
HTTP 405) only `before` callbacks will be executed. The remaining callbacks will
|
3560
|
-
be bypassed.
|
3586
|
+
If a request for a resource is made with an unsupported HTTP method (returning HTTP 405) only `before` callbacks will be executed. The remaining callbacks will be bypassed.
|
3561
3587
|
|
3562
|
-
If a request for a resource is made that triggers the built-in `OPTIONS` handler,
|
3563
|
-
only `before` and `after` callbacks will be executed. The remaining callbacks will
|
3564
|
-
be bypassed.
|
3588
|
+
If a request for a resource is made that triggers the built-in `OPTIONS` handler, only `before` and `after` callbacks will be executed. The remaining callbacks will be bypassed.
|
3565
3589
|
|
3566
3590
|
For example, using a simple `before` block to set a header.
|
3567
3591
|
|
@@ -3706,11 +3730,7 @@ Instead of altering a response, you can also terminate and rewrite it from any c
|
|
3706
3730
|
|
3707
3731
|
## Anchoring
|
3708
3732
|
|
3709
|
-
Grape by default anchors all request paths, which means that the request URL
|
3710
|
-
should match from start to end to match, otherwise a `404 Not Found` is
|
3711
|
-
returned. However, this is sometimes not what you want, because it is not always
|
3712
|
-
known upfront what can be expected from the call. This is because Rack-mount by
|
3713
|
-
default anchors requests to match from the start to the end, or not at all.
|
3733
|
+
Grape by default anchors all request paths, which means that the request URL should match from start to end to match, otherwise a `404 Not Found` is returned. However, this is sometimes not what you want, because it is not always known upfront what can be expected from the call. This is because Rack-mount by default anchors requests to match from the start to the end, or not at all.
|
3714
3734
|
Rails solves this problem by using a `anchor: false` option in your routes.
|
3715
3735
|
In Grape this option can be used as well when a method is defined.
|
3716
3736
|
|
@@ -3726,12 +3746,44 @@ class TwitterAPI < Grape::API
|
|
3726
3746
|
end
|
3727
3747
|
```
|
3728
3748
|
|
3729
|
-
This will match all paths starting with '/statuses/'. There is one caveat though:
|
3730
|
-
the `
|
3731
|
-
|
3732
|
-
|
3733
|
-
|
3734
|
-
|
3749
|
+
This will match all paths starting with '/statuses/'. There is one caveat though: the `params[:status]` parameter only holds the first part of the request url.
|
3750
|
+
Luckily this can be circumvented by using the described above syntax for path specification and using the `PATH_INFO` Rack environment variable, using `env['PATH_INFO']`. This will hold everything that comes after the '/statuses/' part.
|
3751
|
+
|
3752
|
+
## Instance Variables
|
3753
|
+
|
3754
|
+
You can use instance variables to pass information across the various stages of a request. An instance variable set within a `before` validator is accessible within the endpoint's code and can also be utilized within the `rescue_from` handler.
|
3755
|
+
|
3756
|
+
```ruby
|
3757
|
+
class TwitterAPI < Grape::API
|
3758
|
+
before do
|
3759
|
+
@var = 1
|
3760
|
+
end
|
3761
|
+
|
3762
|
+
get '/' do
|
3763
|
+
puts @var # => 1
|
3764
|
+
raise
|
3765
|
+
end
|
3766
|
+
|
3767
|
+
rescue_from :all do
|
3768
|
+
puts @var # => 1
|
3769
|
+
end
|
3770
|
+
end
|
3771
|
+
```
|
3772
|
+
|
3773
|
+
The values of instance variables cannot be shared among various endpoints within the same API. This limitation arises due to Grape generating a new instance for each request made. Consequently, instance variables set within an endpoint during one request differ from those set during a subsequent request, as they exist within separate instances.
|
3774
|
+
|
3775
|
+
```ruby
|
3776
|
+
class TwitterAPI < Grape::API
|
3777
|
+
get '/first' do
|
3778
|
+
@var = 1
|
3779
|
+
puts @var # => 1
|
3780
|
+
end
|
3781
|
+
|
3782
|
+
get '/second' do
|
3783
|
+
puts @var # => nil
|
3784
|
+
end
|
3785
|
+
end
|
3786
|
+
```
|
3735
3787
|
|
3736
3788
|
## Using Custom Middleware
|
3737
3789
|
|
@@ -3940,8 +3992,7 @@ describe Twitter::API do
|
|
3940
3992
|
end
|
3941
3993
|
```
|
3942
3994
|
|
3943
|
-
In Rails, HTTP request tests would go into the `spec/requests` group. You may want your API code to go into
|
3944
|
-
`app/api` - you can match that layout under `spec` by adding the following in `spec/rails_helper.rb`.
|
3995
|
+
In Rails, HTTP request tests would go into the `spec/requests` group. You may want your API code to go into `app/api` - you can match that layout under `spec` by adding the following in `spec/rails_helper.rb`.
|
3945
3996
|
|
3946
3997
|
```ruby
|
3947
3998
|
RSpec.configure do |config|
|
@@ -3975,10 +4026,7 @@ end
|
|
3975
4026
|
|
3976
4027
|
### Stubbing Helpers
|
3977
4028
|
|
3978
|
-
Because helpers are mixed in based on the context when an endpoint is defined, it can
|
3979
|
-
be difficult to stub or mock them for testing. The `Grape::Endpoint.before_each` method
|
3980
|
-
can help by allowing you to define behavior on the endpoint that will run before every
|
3981
|
-
request.
|
4029
|
+
Because helpers are mixed in based on the context when an endpoint is defined, it can be difficult to stub or mock them for testing. The `Grape::Endpoint.before_each` method can help by allowing you to define behavior on the endpoint that will run before every request.
|
3982
4030
|
|
3983
4031
|
```ruby
|
3984
4032
|
describe 'an endpoint that needs helpers stubbed' do
|
@@ -4104,8 +4152,7 @@ Grape integrates with following third-party tools:
|
|
4104
4152
|
|
4105
4153
|
## Contributing to Grape
|
4106
4154
|
|
4107
|
-
Grape is work of hundreds of contributors. You're encouraged to submit pull requests, propose
|
4108
|
-
features and discuss issues.
|
4155
|
+
Grape is work of hundreds of contributors. You're encouraged to submit pull requests, propose features and discuss issues.
|
4109
4156
|
|
4110
4157
|
See [CONTRIBUTING](CONTRIBUTING.md).
|
4111
4158
|
|