Skip to content

Instantly share code, notes, and snippets.

@dsignr
Created May 18, 2016 04:58
Show Gist options
  • Save dsignr/a57c27da6f852751ca83d3d383a04e77 to your computer and use it in GitHub Desktop.
Save dsignr/a57c27da6f852751ca83d3d383a04e77 to your computer and use it in GitHub Desktop.
How to send multipart and json requests to Google Drive API using Ruby's HTTParty
class DriveAPI
include HTTParty
base_uri 'https://www.googleapis.com'
#for debugging
debug_output $stdout
end
def create_file(file_name, parent_id)
check_token!
access_token = current_user.access_token
response = DriveAPI.post(
'/drive/v3/files',
:body => { "mimeType"=> "application/vnd.google-apps.document",
"name"=> "#{file_name}",
"parents"=> ["#{parent_id}"]
}.to_json,
:headers => {
"Authorization" => "Bearer #{access_token}",
"Content-Type" => "application/json"
}
)
response
end
class DriveAPI
include HTTParty
base_uri 'https://www.googleapis.com'
#for debugging
debug_output $stdout
end
#creates a Google document
def upload_file(file_name="xyzabc", parent_id, html)
check_token!
access_token = current_user.access_token
json = { "mimeType"=> "application/vnd.google-apps.document",
"name"=> "#{file_name}",
"parents"=> ["#{parent_id}"]
}.to_json
#Compose multipart body
@boundary = "AaB03x"
post_body = []
post_body << "--#{@boundary}\r\n"
post_body << "Content-Type: application/json"
post_body << "\r\n\r\n"
post_body << json
post_body << "\r\n--#{@boundary}\r\n"
post_body << "Content-Type: text/html"
post_body << "\r\n\r\n"
post_body << html
post_body << "\r\n--#{@boundary}--\r\n"
body = post_body.join
response = DriveAPI.post(
'/upload/drive/v3/files?uploadType=multipart',
:body => body,
:headers => {
"Authorization" => "Bearer #{access_token}",
"Content-Type" => "multipart/related; boundary=#{@boundary}"
}
)
response
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment