1

I've searched many other questions and I don't see that I'm doing anything different, but rest-client will not work when trying to post a new event to Google API

url = "https://www.googleapis.com/calendar/v3/calendars/primary/events?access_token=#{token}"
params = {start: 'test'}.to_json
response = RestClient.post url, params

RestClient::BadRequest (400 Bad Request)
A B
  • 8,340
  • 2
  • 31
  • 35
justindfunk
  • 83
  • 2
  • 4
  • [400: Bad Request](https://developers.google.com/drive/v3/web/handle-errors#400_bad_request) error means that a required field or parameter has not been provided, the value supplied is invalid, or the combination of provided fields is invalid. This [GitHub issue](https://github.com/recurser/pivotal-to-trello/issues/2) suggested to try switching to ssl: `PivotalTracker::Client.use_ssl = true`. This [SO post](http://stackoverflow.com/questions/35176313/rails-restclient-post-request-failing-with-400-bad-request) might also help. – abielita Dec 10 '16 at 18:42

1 Answers1

1

Note that you may be interested in using Google's own client library for Ruby instead of just RestClient:

https://developers.google.com/api-client-library/ruby/start/installation


Solving the issue with RestClient

You can pull the error message out of the HTTP 400 exception.

Here's what I see:

auth_header 'Bearer zzzz...'
base_url = 'https://www.googleapis.com/calendar/v3/calendars/primary'
event = {'summary': 'Test RestClient event', 'start': {'dateTime': Time.now.strftime('%FT%T%z')}, 'end': {'dateTime': (Time.now + 3600).strftime('%FT%T%z')}}

begin
  RestClient.post(base_url + '/events', event.to_json, {authorization: auth_header})
rescue RestClient::BadRequest => err
  puts err.response.body
end

Which prints this HTTP 400 response:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "This API does not support parsing form-encoded input."
   }
  ],
  "code": 400,
  "message": "This API does not support parsing form-encoded input."
 }
}

What's going on here? RestClient assumes that you want a request Content-Type of application/x-www-form-urlencoded unless you specify otherwise.

So if we add the correct Content-Type: application/json header, everything works as expected:

>> RestClient.post(base_url + '/events', event.to_json, {authorization: auth_header, content_type: :json})
=> <RestClient::Response 200 "{\n \"kind\": ...">

Removed prior answer which didn't solve the problem

A B
  • 8,340
  • 2
  • 31
  • 35
  • I've seen other examples that do. I also tried moving it, taking it out of the url and changing params to: `params = {access_token: token, start: "test"}.to_json` and got Unauthorized error. – justindfunk Dec 10 '16 at 21:06