Created
May 18, 2016 04:58
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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