POST json to rails server
If you are sending in the right headers, then you won't need to do "ActiveSupport::JSON.decode" -- rails will do that for you.
You'll need to set the following headers in your post.
Content-Type: application/json
Accept: application/json
A 422 means Unprocessable Entity --- generally that there was a validation failure.
You should be able to have. If you can't, then your headers aren't set correctly.
def create
if user = User.authenticate(params["email"], params["password"])
session[:user_id] = user.id
render :json => "{\"r\": \"t\"}" + req
else
render :json => "{\"r\": \"f\"}"
end
end
How can I POST json data from android app to Ruby on Rails server
Welcome to S.O.!
So, there's a few things that need addressing here. For starters, in your controller:
# For creating an expense from the android app
def post_json_expense
Expense.new(expense_params)
end
So, first, calling Expense.new
here will only create a new object, but it will not persist it to the database; you'll also need to call save
to do that.
Next, you are not returning any sort of response back to the caller. Perhaps returning something like the id of the new Expense would be in order, or the expense itself. I'd suggest constructing the call like so:
# For creating an expense from the android app
def post_json_expense
expense = Expense.new(expense_params)
unless expense.save
# TODO: Return an error status with some useful details
# You can get some from expense.errors
return render status: 400, json: { error: true }
end
# Render a JSON representation of the expense on successful save
render json: expense.as_json
end
Next, on the client side, you are sending Content-type
headers, which is good, but you could also send Accept
headers, which clues the server as to what you expect to receive back:
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Accept", "application/json");
return params;
}
Finally, you have assigned the method to the POST route on your server:
post '/api' => 'expenses#post_json_expense'
But you are calling it as a PUT from your app:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, expenseObject, new Response.Listener<JSONObject>() {
So, there is no PUT
route at that URL, hence why the request would always fail.
Cleaning up these issues should get you a successful response.
Personally, I find using a simple utility like curl
often helps debug these sort of communication errors, when you don't know whether the issue is the fault of an app-side coding issue or a server-side coding issue (or both). You can eliminate the variables by using something like curl
which you can be confident works, then debug from there.
Hope this helps you along!
POSTing json data and file to Ruby on Rails API
Problem ended up being that I needed a view which would contain a form. You know, so that the formdata request has something to actually submit to...... Dumb mistake. Learned my lesson
Posting JSON with file content on Ruby / Rails
Here is how I solved this problem. First I created a rake task to upload the file within the json content:
desc "Tests JSON uploads with attached files on multipart formats"
task :picture => :environment do
file = File.open(Rails.root.join('lib', 'assets', 'photo.jpg'))
data = {title: "Something", description: "Else", file_content: Base64.encode64(file.read)}.to_json
req = Net::HTTP::Post.new("/users.json", {"Content-Type" => "application/json", 'Accept' => '*/*'})
req.body = data
response = Net::HTTP.new("localhost", "3000").start {|http| http.request(req) }
puts response.body
end
And then got this on the controller/model of my rails app, like this:
params[:user] = JSON.parse(request.body.read)
...
class User < ActiveRecord::Base
...
has_attached_file :picture, formats: {medium: "300x300#", thumb: "100#100"}
def file_content=(c)
filename = "#{Time.now.to_f.to_s.gsub('.', '_')}.jpg"
File.open("/tmp/#{filename}", 'wb') {|f| f.write(Base64.decode64(c).strip) }
self.picture = File.open("/tmp/#{filename}", 'r')
end
end
elm post json to rails
It seems, that Rails
expects your input to be something like:
{
score: {
name: "Larry",
score: 100
}
}
But you're passing just { name: "Larry", score: 100 }
, thus required score
key is missing.
One of the options is to enhance your encoder into something like:
encodeScore : Model -> Encode.Value
encodeScore model =
Encode.object
[ ( "score"
, Encode.object
[ ( "name", Encode.string model.name )
, ( "score", Encode.int (sumMarkedPoints model.entries) )
]
)
]
Posting JSON data to rails controller?
Your problem is that your controller is expecting parameters related to a trip
to be in params[:trip]
.
Change your json to be
trip: {
title: 'Charlie'
}
and I think that will fix it for you.
i.e. your params should look like params => {:trip => {:title => 'Charlie}}
Posting json requests to Ruby on Rails server app – 500 error
According to the server logs, there was a NoMethodError – stringify_keys. This question's answer was the solution: undefined method `stringify_keys'
Changing@request = Request.new(params[:request])
to@request = Request.new(:request => params[:request])
did the trick.
Related Topics
How to Switch to Ruby 1.9.3 Installed Using Homebrew
Nokogiri, Open-Uri, and Unicode Characters
Why Does Adding "Sleep 1" in an After Hook Cause This Rspec/Capybara Test to Pass
To Use Self. or Not.. in Rails
Understanding Ruby and Os I/O Buffering
Can Ruby Print Out Time Difference (Duration) Readily
How to Use Gem to Install Rails on Ubuntu
Installed Ruby Using Apt-Get Install Ruby 2.0.0 Succeeded But Not Using Correct Ruby Version
Ruby Array Subtraction Without Removing Items More Than Once
How to Set Up the Database.Yml File in Rails
When Do I Need to Restart Server in Rails
Convert Array of 2-Element Arrays into a Hash, Where Duplicate Keys Append Additional Values