Nubtacular
Nubtacular

Reputation: 1397

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

http://localhost:3000/phone_number_lookup/1234567890

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:

http://myremoteURL.com/Service/?Param1=sSerialNumber&Param2=iVideoSystemID&Param3=sMAC&Param4=ItemID

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?

Upvotes: 1

Views: 811

Answers (2)

Jason Noble
Jason Noble

Reputation: 3766

Could you modify the JSON response?

{
  "AccountCode": "1234",
  "AccountID": 13579,
  ...
  "id": null
  "follow_up_url": "http://myremoteURL.com/Service/?Param1=sSerialNumber&Param2=iVideoSystemID&Param3=sMAC&Param4=ItemID"
}

This allows your JSON to tell the requester "where to go next".

Upvotes: 0

Yaro
Yaro

Reputation: 568

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",
 "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"=>nil}

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.

Upvotes: 2

Related Questions