How to parse incoming JSON from my controller? - ruby-on-rails

I am JSON posting the following JSON to my controller:
{"user_id": 234324, "user_action": 2, "updated_email": "asdf#asdf.com" }
In my controller I can see the JSON is correctly POSTED but I am not sure how to access it:
def update_email
puts request.body.read.html_safe
user_id = params[:user_id]
user = User.find(user_id)
end
I am testing this in my controller_spec and currently it is throwing an exception and is showing the id is empty.

This may be a duplicate - see: How do I parse JSON with Ruby on Rails?
I'm not sure how you're passing the JSON. Is it part of the POST params? In the header? Or something else. My guess is that you're either passing it as a param or should do so: e.g. myJson = {"user_id": 234324, "user_action": 2, "updated_email": "asdf#asdf.com" }
As far as parsing it goes, you should be able to use the built-in JSON class for this.
hash = JSON.parse params["myJson"]

Accessing it with params is the right way.
In your case:
params["user_id"] # => 234324
request.body.read shouldn't be used in real world, just for debugging, as action_dispatch does all the dispatch for you (like parse JSON or form data).
Note: you need to have the correct headers set, to let rails know that you're passing JSON.

Related

How to pass nested arrays over http via HTTParty in Rails 4 application

I call a controller action "passit" of Rails app A and want to pass an array b to an api update call via an HTTP request using the HTTParty gem patch method:
def passit
b=[[1,2,3],[4,5,6]]
params["a"] = b.to_json
id=5
#options = {query: params}
#response = HTTParty.patch("someapi.com/#{id}", #options)
end
The only way I have found to pass b so far so that a value other than nil gets passed to the API is to stringify it via to_json.
Is the only way to pass a nested array via a patch/put/some kind of update request over http is to "stringify" the parameter via JSON or converting it to a string?
Have a look at Marshal. That allows you to convert objects into byte streams that you can then transfer more easily.

Rails display JSON from an api GET request

I'm a rails beginner and I'm trying to display a json object I get back from an external api. I'm using HTTParty and I'm almost positive I have that set up correctly. I have a function in my HTTParty class called
self.get_all()
How would I go about making a new page on which to display the JSON I get back from that function?
It all pretty much depends on the json that comes back. Aside from it being 'JSON`, what does it look like? If you haven't even inspected it yet, maybe that's a good place to start. You can call your method like so: (pick one)
puts your_httparty_class.get_all.inpsect # will be displayed in your logs (most likely)
raise your_httparty_class.get_all.inspect # will raise the response to the view
You may find yourself needing to do something like this to ensure it's a hash.
response = HTTParty.get('https://api.somesite.com/some_endpoint')
body = JSON.parse(response.body)
Now that you know and can see that the JSON is just a hash you can access it like so:
something = body[:something] # accessing a hash
nested_something = body[:something][:nested_something] # accessing a nested hash
You can then move something and nested_something around your app. So, you could pass it from your controller to your view as instance variables:
# # makes it an instance variable and therefore accessible to your controller's views
#something = body[:something]
#nested_something = body[:something][:nested_something]

Accessing Variables in Rails 3 before_save Method

I have the following before_save method:
def get_data
url = "http://www.api-fetching-url.com/where_my_data_input_is=#{self.my_data}&output=json"
new_data = HTTParty.get(url)
#field_to_update = new_data['one']['two']['here']
self.field_to_update = #field_to_update
end
Unfortunately, the self.my_data doesn't appear to be working, because the JSON url doesn't produce any result. But, when I substitute my_data in the hardcoded way, it works just fine. Moreover, I can do a find in the Rails console and get the my_data field just fine. So, it's not an issue with that field not saving or something on the form side.
Is there an issue inserting data this way in a before_save method? If not, is there a different way of doing this that I'm missing?
Some remarks:
You don't have to (and actually can't) always call methods with the self receiver. Private methods for example can only be called without an explicit receiver, so no self. for private methods...
Why don't you inspect the url and check whether it is correct? Just add puts url after the line where you assign the url, run your program and check the output. Is the url correct?
You probably use HTTParty not correctly: HTTParty.get('...') returns a response object and you probably have to parse the response's body properly.
An example for a JSON service:
url = 'http://service.com/path/to/resource.json'
response = HTTParty.get url
data = JSON.parse(response.body)
# now you can use the data, e.g.
# bla = data['one']['foo']

Rails: Getting the JSON object after making a post request

I'm a beginner Rails programmer and even though this question might be too easy, I love to know if it's possible and if it is how can I accomplish that?
My question inside the index how can I make a get request to a link and assign it's JSON response to an object that I will be later using on. The syntax(not correct) I had in my mind was something like;
people=Make_A_Get_Request("http://people.com") //It will return in JSON
#peopleName=people['name']
I know that it's not true but is there like any method I can apply in Rails like the one above to make a get request to a link and assign its JSON response to an object in my rails function
Try something like below
def index
uri = URI('http://people.com/path/to/request')
response = Net::HTTP.get(uri)
data = JSON.parse(response.body)
#then you can play like data["name"]
rescue Exception => e
logger.info "Unable to do something due to #{e.message}"
end

Serializing Simple JSON String with Rails ActiveResource

I have a RESTful API call that acts like this:
HTTP GET http://addresss:port/settings/{setting}
which returns just the value of the setting specified as a simple string:
"settingValue"
I want to retrieve this value using a subclass of ActiveResource:Base
class Settings < ActiveResource:Base
self.site = CONFIG['uri']
self.collection_name = 'settings'
self.format = :json
...
end
But when I call Settings.find("Setting"), I get unexpected token at '"settingValue"'.
I could change the format of the data returned from the API, but is there anyway to get Rails to correctly handle this data?
Your api doesn't render json so Active Resource fails when it tries to parse a mere text.
Use another means to communicate with apis like restclient

Resources