Skip to content

Commit 0f904bf

Browse files
committed
Added an example that preprocesses params sent as JSON data.
1 parent dccf93d commit 0f904bf

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ A [Grape](http://github.com/ruby-grape/grape) API mounted on Rack.
1010
* [ping](api/ping.rb): a hello world example that returns a JSON document
1111
* [post_put](api/post_put.rb): a simple `POST` and `PUT` example
1212
* [post_json](api/post_json.rb): an example that shows a `POST` of JSON data
13+
* [get_json](api/get_json.rb): an example that pre-processes params sent as JSON data
1314
* [rescue_from](api/rescue_from.rb): an example of `rescue_from` that wraps all exceptions in an HTTP error code 500
1415
* [path_versioning](api/path_versioning.rb): an example that uses path-based versioning
1516
* [header_versioning](api/header_versioning.rb): an example that uses vendor header-based versioning

api/get_json.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
module Acme
2+
class GetJson < Grape::API
3+
format :json
4+
desc 'Flips reticulated in a collection of splines passed as JSON in a query string.'
5+
resource :reticulated_splines do
6+
before do
7+
params.each_pair do |k, v|
8+
params[k] = JSON.parse(v) rescue v
9+
end
10+
end
11+
params do
12+
requires :splines, type: Array do
13+
requires :id, type: Integer
14+
requires :reticulated, type: Boolean
15+
end
16+
end
17+
get do
18+
params[:splines].map do |spline|
19+
spline.merge(reticulated: !spline[:reticulated])
20+
end
21+
end
22+
end
23+
end
24+
end

app/api.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ class API < Grape::API
99
mount ::Acme::PostPut
1010
mount ::Acme::WrapResponse
1111
mount ::Acme::PostJson
12+
mount ::Acme::GetJson
1213
mount ::Acme::ContentType
1314
mount ::Acme::UploadFile
1415
mount ::Acme::Entities::API

spec/api/get_json_spec.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
require 'spec_helper'
2+
3+
describe Acme::API do
4+
include Rack::Test::Methods
5+
6+
def app
7+
Acme::API
8+
end
9+
10+
it 'flips reticulated in a collection of splines' do
11+
get '/api/reticulated_splines', 'splines' => [
12+
{ id: 1, reticulated: false },
13+
{ id: 2, reticulated: true }
14+
].to_json
15+
expect(last_response.status).to eq(200)
16+
expect(last_response.body).to eq([
17+
{ id: 1, reticulated: true },
18+
{ id: 2, reticulated: false }
19+
].to_json)
20+
end
21+
end

0 commit comments

Comments
 (0)