Skip to content

Commit e6db7e7

Browse files
author
Robert Ross
committed
- Add ability to get request bodies as parameters.
- Add spec to make sure body_params does not include parameters defined by the route.
1 parent 346fb94 commit e6db7e7

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

lib/grape/endpoint.rb

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,26 @@ def call!(env)
118118
# The parameters passed into the request as
119119
# well as parsed from URL segments.
120120
def params
121-
@params ||= Hashie::Mash.new.deep_merge(request.params).deep_merge(env['rack.routing_args'] || {})
121+
@params ||= Hashie::Mash.new.
122+
deep_merge(request.params).
123+
deep_merge(env['rack.routing_args'] || {}).
124+
deep_merge(self.body_params)
125+
end
126+
127+
# Pull out request body params if the content type matches and we're on a POST or PUT
128+
def body_params
129+
if ['POST', 'PUT'].include?(request.request_method.to_s.upcase)
130+
return case env['CONTENT_TYPE']
131+
when 'application/json'
132+
MultiJson.decode(request.body.read)
133+
when 'application/xml'
134+
MultiXml.parse(request.body.read)
135+
else
136+
{}
137+
end
138+
end
139+
140+
{}
122141
end
123142

124143
# The API version as specified in the URL.

spec/grape/endpoint_spec.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,31 @@ def app; subject end
167167

168168
get '[email protected]/wrong_middle/1'
169169
last_response.status.should == 404
170+
end
171+
end
172+
173+
context 'from body parameters' do
174+
before(:each) do
175+
subject.post '/request_body' do
176+
params[:user]
177+
end
178+
end
170179

180+
it 'should convert JSON bodies to params' do
181+
post '/request_body', MultiJson.encode(user: 'Bobby T.'), {'CONTENT_TYPE' => 'application/json'}
182+
last_response.body.should == 'Bobby T.'
183+
end
184+
185+
it 'should convert XML bodies to params' do
186+
post '/request_body', '<user>Bobby T.</user>', {'CONTENT_TYPE' => 'application/xml'}
187+
last_response.body.should == 'Bobby T.'
188+
end
189+
190+
it 'does not include parameters not defined by the body' do
191+
subject.post '/omitted_params' do
192+
body_params[:version].should == nil
193+
end
194+
post '/omitted_params', MultiJson.encode(user: 'Blah'), {'CONTENT_TYPE' => 'application/json'}
171195
end
172196
end
173197
end

0 commit comments

Comments
 (0)