DnfD DnfD - 11 months ago 45
JSON Question

Rails 4 API, how to create a URL from a JSON response?

I'm working on an API where I have a few routes setup, ie


which can return a JSON response like so:

"AccountCode": "1234",
"AccountID": 13579,
"BalanceCurrent": "5000",
"Phone": "1234567890",
"Id": 123123,
"SerialNumber": "Y2K2000XY2016",
"MACADDRESS": "y2k2000xy2016",
"EQUIPMENTTYPE_Name": "Motorola DCX100 HD DVR",
"ADDRESS_Zip": "90210",
"ItemID": 12345,
"iVideoSystemID": 1000001
"id": null

The next 'step' of the API consumption would be, 'given the initially returned response, use 4 of those parameters and pass them into a remote URL that will then do something.'

Like so:


It would be one thing to just set up a route that takes 4 parameters, but the route needs to be contingent on what the initial JSON response was.

What is the proper way to do this?

Answer Source

First of all, you'll have to convert your JSON to hash. Something like this will do:

[7] pry(main)> hash=JSON.parse(json)
=> {"AccountCode"=>"1234",
 "EQUIPMENTTYPE_Name"=>"Motorola DCX100 HD DVR",

Then you'll have to choose 4 parameters to send. I just took last 4 parameters

[14] pry(main)> chosen_params = hash.slice("ItemID", "id", "iVideoSystemID", "ADDRESS_Zip")
=> {"ItemID"=>12345, "id"=>nil, "iVideoSystemID"=>1000001, "ADDRESS_Zip"=>"90210"}

Then you'll have to pass them to your remote url. This can be done using a helper described here. Then you'll have to just do something like generate_url("YOUR-URL-ADDR-HERE", chosen_params). At this point you might want to change the generate_url helper in a way you need it to be to generate the url you need. Maybe it should take third parameter called action which will then generate url like http://www.google.com/action?{chosen_params}

The result will be:

[23] pry(main)> generate_url("http://www.google.com", chosen_params)
=> "http://www.google.com?ADDRESS_Zip=90210&ItemID=12345&iVideoSystemID=1000001&id="

Hope it helps. Let me know about any questions.