justindfunk
justindfunk

Reputation: 83

Rails POST to Google Calender API via rest-client gives 'bad request' error

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)

Upvotes: 1

Views: 672

Answers (1)

A B
A B

Reputation: 8866

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

Upvotes: 1

Related Questions