sironekotoroの日記

Perl で楽をしたい

Perl で Google Drive API をつかってフォルダーを作成する

はい、慣れてきました。

API の URL と mimeType 以外はそのまんまです。

my $GOOGLE_DRIVE_API
    = "https://www.googleapis.com/upload/drive/v3/files?create";

# (中略)

          `mimeType => 'application/vnd.google-apps.folder',`

developers.google.com

To create a folder, use the files.create method with the application/vnd.google-apps.folder MIME type and a title.

(DeepL翻訳)フォルダを作成するには、files.create メソッドを使用して、application/vnd.google-apps.folder MIME タイプとタイトルを指定します。

#!/usr/bin/env perl
use strict;
use warnings;

binmode STDOUT, ":utf8";

use HTTP::Request::Common;
use JSON qw/encode_json/;
use LWP::UserAgent;

my $GOOGLE_DRIVE_API
    = "https://www.googleapis.com/upload/drive/v3/files?create";
my $ACCESS_TOKEN    = "";

my $bearer = join ' ', ('Bearer', $ACCESS_TOKEN);

my $ua = LWP::UserAgent->new;
my $res = $ua->request(
    POST $GOOGLE_DRIVE_API,
    'Content-Type' => 'multipart/form-data',
    Authorization => $bearer,
    Content => [

        metadata => [
            undef,
            undef,
            'Content-Type' => 'application/json;charset=UTF-8',
            'Content' => encode_json(
                {
                    name     => 'create_folder_test',
                    mimeType => 'application/vnd.google-apps.folder',
                    parents  => ['10kCqEUmWsWlqMdP_vF9pDGrQXFVZ-Lvr'],
                },
            ),
        ],

    ],
);

print  $res->code . "\n";
print  $res->content . "\n";

# 200
# {
#  "kind": "drive#file",
#  "id": "1cJ1jQOQ9KAqxVPJwIWNhGuXH1BBA9k2M",
#  "name": "create_folder_test",
#  "mimeType": "application/vnd.google-apps.folder"
# }