ruby on rails - How do I force Grape to accept and return only JSON? -



ruby on rails - How do I force Grape to accept and return only JSON? -

how restrict api take & respond json format on rails & grape, i've seek format :json on grape controller , (for example) can access on example.com/api/v1/ping.json, can access via example.com/api/v1/ping.xml, example.com/api/v1/ping.foobar, , list of extensions goes on...

the things is, throwing error on example.com/api/v1/ping.not_json_extensions

im using:

rails (4.1.1) grape (0.7.0)

/config/routes.rb

mount api::base => '/api'

/controllers/api/base.rb

module api class base of operations < grape::api mount api::v1::base end end

/controllers/api/v1/base.rb

module api module v1 class base of operations < grape::api format :json mount api::v1::ping end end

end

/controllers/api/v1/ping.rb

module api module v1 class ping < grape::api include api::v1::defaults desc 'returns pong.' :ping { ping: params[:pong] || 'pong' } end end end

end

looking @ grape's source code, seems intended behaviour alter prevent memory leaks broke it.

you can implement right behaviour "manually" adding explicit check api class (in /controllers/api/base.rb):

before # create sure format specified request extension 1 # back upwards parts = request.path.split('.') if parts.size > 1 extension = parts.last if !extension.eql? 'json' throw :error, { status: 406, message: "the requested format '#{extension}' not supported." } end end end

this code copied pretty much verbatim grape's source (in lib/grape/middleware/formatter.rb) , how grape checks extension used in request.

in file, negotiate_content_type responsible checking whether requested format 1 supported api, , gives priority request extension. method parses extension uri, format_from_extension, also checks whether format supported , returns nil if isn't, though there no extension @ all. result negotiate_content_type never trigger error if request's extension specifies unsupported format, though meant so.

you can "fix" changing code @ formatter.rb:109 from

# avoid symbol memory leak on unknown format homecoming extension.to_sym if content_type_for(extension)

to simply

return extension.to_sym

the comment suggests code written way reason, though, proceed caution.

ruby-on-rails ruby routes grape grape-api

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -