Lumbee Lumbee - 26 days ago 12
JSON Question

Using Google Apps Script to Post JSON Data in Rails 5

I have the following Google Apps Script:

function myFunction() {
var payload =
{
"person": {
"first_name": "test",
"last_name": "blah"
}
};

var options =
{
"method" : "post",
"contentType" : "application/json",
"payload" : payload
};

var response = UrlFetchApp.fetch("https://myappherokuapp.com/curl_example", options);
Logger.log(response);
}


The app I am posting to is a Rails 5 app. The error I am getting when I run the script is...

Request failed for https://myherokuapp.com/curl_example returned code 400


...and on heroku this is what I am seeing in the logs...

2016-11-09T16:43:37.966300+00:00 heroku[router]: at=info method=POST path="/curl_example" host=myherokuapp.com request_id=51c138b5-ed30-4d4b-aa61-b477de875695 fwd="75.143.171.231,107.178.224.13" dyno=web.1 connect=0ms service=19ms status=400 bytes=179
2016-11-09T16:43:37.960171+00:00 app[web.1]: person=%7Blast_name%3Dblah,+first_name%3Dtest%7D


I can run this curl command and successfully post data:

curl -X POST -d "person[first_name]=john" -d "person[last_name]=doe" https://myherokuapp.com/curl_example


Also here is my controller in Rails...

class PeopleController < ApplicationController
before_action :set_person, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token, :only => [:curl_post_example]
...
def curl_post_example
Person.create(person_params)
render plain: "Thanks for sending a POST request with cURL! Payload: #{request.body.read}"
end
...

Answer

You should stringify the payload if you use the "application/json" content type. Or omit the content type, then it will be transferred as 'application/x-www-form-urlencoded'.

I am not sure what the Rails app expect, but the current request is invalid because it expects a json string.