Serializing Simple JSON String with Rails ActiveResource - ruby-on-rails

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

Related

How to parse incoming JSON from my controller?

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.

Rails API and Strong PARAMS

I am trying to create an api to create record Foo using the rails-api gem.
I initially ran the generator command to tell rails to create a controller for me and it created this:
def create
#foo = Foo.new(foo_params)
#foo.save
respond_with(#foo)
end
And this (Strong params):
def foo_params
params.require(:foo).permit(:bar)
end
This is pretty standard stuff and will work when using form_for to submit data to the create method.
In my case, I'm creating a stand-alone API web service that will only interact via external API calls.
So the issue that I'm experiencing, is I don't know how to post the :bar param via API. I tried posting a :bar param, but this leads to a 'param is missing or the value is empty: foo' error. I understand why this is happening, but I have no idea how to get around this...
Is there a better way to do this or should I provide the api param in a different way?
PS. Currently my api POST call looks like this:
http://localhost:3000/api/v1/foo.json?bar=test#mail.com
you cannot use the ?+argument at the end of the url for a POST HTTP request, it's only for a GET request.
You must use the data component of the HTTP call, that is not embedded in the URL
therefore, you cannot just make this from your browser address bar and must use curl or a great tool as Postman (free on the chrome App Store)
and in this data field, you can include the object you want to post (postman gives you a neat key value interface to do so)
let me know if you need more details on the curl function for command line calls, but I recommend that you use a nice tool as Postman, so useful if you're not used to these calls
EDIT : this is the URL to get Postman : https://www.getpostman.com

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']

Resources