Processing JSON or XML in Rails - ruby-on-rails

I am uploading JSON data to a rails app through an HTTP Post.I am a rails newbie and I do not understand how to process json or xml in the controller of my rails app. I can find info for processing form data, but not posted json or xml. please direct me to a book, tutorial, guide or code that tackels this problem. Thanks.

As long as you are correctly setting the content type header in the HTTP Post, any XML or JSON should be parsed automatically and placed in the params hash which is then available in the action (in the controller).
For example, if you put this in the content body:
{
'name': 'John',
'occupation': 'foe'
}
... and set the content type header to application/json when making the HTTP Post, then you can do something like this in your controller:
def process
#person = Person.new
#person.first_name = params['name']
#person.occupation = params['occupation']
end

Related

Rails-API How to test Active Storage

I added Active Storage into my Rails API application and want to test it, but I don't know how to do it. I was trying send file with JSON data in Postman, but JSON data doesn't send correctly or I am doing something wrong. I did it like that:
Image from postman
Is there any option to send request with file and JSON data without creating any view?
As far as I know, an upload can't be done via an API rest way. You need to use enctype: multipart/form-data as regular POST done via form.
In your screenshot you are already sending as form-post, because you chose to send via form-data. This is why your json isn't properly parsed by rails.
If you want to upload an image and post data in the same request you will need to break your json attributes into form data fields like:
data[name]=asaa
data[last_name]=foo
...
Or, you can send a JSON in your data field and do the manual parsing when fetching in controller like:
def upload
file = params[:file]
data = parsed_params_data!(params)
# do your magic
end
def parsed_params_data!(params)
JSON.parse(params[:data])
end

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.

How to access Rails params before all of the values are stringified?

I'd like to be able to inspect the params hash before all of the values are stringified by Rails. For example if I am using application/json Accept/Content-Type, and I receive:
{ "id":1, "post":"Hello" }
I want to be able to know that params[:id] was originally passed as a JSON integer, not a string.
I also want to be able to do this within a controller spec, which uses a limited set of middleware (or none at all?). Is this possible?
I believe this post has what you are looking for: How to access the raw unaltered http POST data in Rails?
request.raw_post
http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-raw_post

Reading and Setting Rails Response Headers

I want to read the header of a request coming in to a Rails Controller...
How can I read in the header of the request to see what the request expects/wants back (in terms of formats) and send back data in that format?
example:
#in the controller receiving the request
def receive_req
request.head #read value from header
#if req wants json, format to json else, format to html etc...
res = response
res.head = "set appropriate header values"
res.body = "data to send back in the body"
end
#in the controller making the req
def send_request
Net::HTTP.post("/receive_req", "data", header_values)
render #{response.body}
end
Use the request.headers hash as described here.
Of course, you might also choose to define your routes in such a manner that each endpoint provides output in only one format. Whatever works for your application.

Finding form fields in a Rails POST request

I'm using a plain old HTML form to send a post request to a rails app. Inside the app I would like to grab some of the input fields. I'm having trouble finding them inside the request.
Trying this:
logger.debug "Request Headers #{request.headers.inspect}"
Spits out a massive amount of data but I cannot find my form fields in there. Does anyone know where I can find them?
You can grab the request parameters submitted using:
logger.debug params.inspect
That will show all the form data submitted.

Resources