How to parse JSON request body in Sinatra just once and expose it to all routes?

前端 未结 5 1880
暗喜
暗喜 2020-12-15 16:12

I am writing an API and it receives a JSON payload as the request body.

To get at it currently, I am doing something like this:

post \'/doSomething\'         


        
相关标签:
5条回答
  • 2020-12-15 16:16

    You can also use Rack Middleware to parse it. See https://github.com/rack/rack-contrib Just use Rack::PostBodyContentTypeParser when initializing your Sinatra class.

    0 讨论(0)
  • 2020-12-15 16:17
    before do
      request.body.rewind
      @request_payload = JSON.parse(request.body.read, symbolize_names: true)
    end
    

    So you can also symbolize_names while parsing JSON request body, this will give you access to your nested params like this @request_payload[:user]

    0 讨论(0)
  • 2020-12-15 16:21

    You can parse your JSON post body as a Hash with Rack::PostBodyContentTypeParser from https://github.com/rack/rack-contrib:

    require 'rack/contrib/post_body_content_type_parser'
    
    class Api < Sinatra::Application
      use Rack::PostBodyContentTypeParser
      ...
    end
    

    You can even pass a custom block to Rack::PostBodyContentTypeParser to parse the JSON as symbols instead of strings:

    a_proc = proc { |body| JSON.parse(body, symbolize_names: true, create_additions: false) }
    use Rack::PostBodyContentTypeParser, &a_proc
    
    0 讨论(0)
  • 2020-12-15 16:25

    Like this working for sinatra 1.4.5

    before do
      if request.body.size > 0
        request.body.rewind
        @params = ActiveSupport::JSON.decode(request.body.read)
      end
    end
    
    0 讨论(0)
  • 2020-12-15 16:36

    Use a sinatra before handler:

    before do
      request.body.rewind
      @request_payload = JSON.parse request.body.read
    end
    

    this will expose it to the current request handler. If you want it exposed to all handlers, put it in a superclass and extend that class in your handlers.

    0 讨论(0)
提交回复
热议问题