Ruby send JSON request

后端 未结 10 1341
后悔当初
后悔当初 2020-11-28 20:37

How do I send a JSON request in ruby? I have a JSON object but I dont think I can just do .send. Do I have to have javascript send the form?

Or can I us

10条回答
  •  清歌不尽
    2020-11-28 21:06

    It's 2020 - nobody should be using Net::HTTP any more and all answers seem to be saying so, use a more high level gem such as Faraday - Github


    That said, what I like to do is a wrapper around the HTTP api call,something that's called like

    rv = Transporter::FaradayHttp[url, options]

    because this allows me to fake HTTP calls without additional dependencies, ie:

      if InfoSig.env?(:test) && !(url.to_s =~ /localhost/)
        response_body = FakerForTests[url: url, options: options]
    
      else
        conn = Faraday::Connection.new url, connection_options
    

    Where the faker looks something like this

    I know there are HTTP mocking/stubbing frameworks, but at least when I researched last time they didn't allow me to validate requests efficiently and they were just for HTTP, not for example for raw TCP exchanges, this system allows me to have a unified framework for all API communication.


    Assuming you just want to quick&dirty convert a hash to json, send the json to a remote host to test an API and parse response to ruby this is probably fastest way without involving additional gems:

    JSON.load `curl -H 'Content-Type:application/json' -H 'Accept:application/json' -X POST localhost:3000/simple_api -d '#{message.to_json}'`
    

    Hopefully this goes without saying, but don't use this in production.

提交回复
热议问题