This is a question "why does it work this way", not "how do I make this work".
My app is calling a third party REST API that returns JSON, and returning the result as part of my own JSON API.
I was using the Rails 3 respond_to
and respond_with
methods; in the case of GET
requests, this works as I expect, just passing through the JSON.
In the case of POST
, it does more, including making a URL from the object returned to pass in a :location
option. But since my object is just JSON (not ActiveRecord), I get an error.
For example...
# POST /api/products.json with params id=:id
def create
query_string = "#{user_id}&id=#{params[:id]}"
@products = third_party_api_wrapper.products(query_string, 'POST')
respond_with @products
end
My wrapper for the 3rd party API makes a POST request, which comes back fine, then Rails returns a 500 error which is logged like this:
NoMethodError (undefined method `{"response":{"message":"product 4e1712d9ec0f257c510013f8 selected"}}_url' for #<MyController>
Rails want's my @products object to know how to make a location URL.
CLARIFICATION: The @products
object returned by the third party API is pure JSON -- a string, which you can see embedded in the error log message above. This error is occurring because Rails seems to want the object to be something more -- in the Rails internal API support, it is an ActiveRecord object.
If I replace the new respond_with
with sytax with the old-style
respond_to do |format|
format.json { render :json => @products } # note, no :location or :status options
end
then everything works. And this is what I have done, so I don't have a "how" problem, instead have a "why" question.
Ryan Daigle's post on the introduction explains that what's happening is expected.
My question is: why does respond_with
expect anything other than data (and the HTTP status?), and apparently just for POST
.
I am not saying it's wrong, just trying to understand the rationale for the Rails implementation.
respond_with
did not work for you? (2) saying the 3rd party API you are using does not return "just" data and a status code? (3) asking "why should an API return anything other than data ?" – Heraldry@products
and tell us the result. – Heraldry