Panduan memulai Python

Tetap teratur dengan koleksi Simpan dan kategorikan konten berdasarkan preferensi Anda.

Panduan memulai menjelaskan cara menyiapkan dan menjalankan aplikasi yang memanggil Google Workspace API.

Panduan memulai Google Workspace menggunakan library klien API untuk menangani beberapa detail alur autentikasi dan otorisasi. Sebaiknya gunakan library klien untuk aplikasi Anda sendiri. Sebelum dapat menjalankan aplikasi contoh, setiap panduan memulai mengharuskan Anda mengaktifkan autentikasi dan otorisasi. Jika Anda tidak memahami autentikasi dan otorisasi untuk Google Workspace API, baca Ringkasan autentikasi dan otorisasi.

Membuat aplikasi command line Python yang membuat permintaan ke Google Apps Script API.

Tujuan

  • Siapkan lingkungan Anda.
  • Instal library klien
  • Siapkan contoh.
  • Jalankan contoh.

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan prasyarat berikut:

  • Akun Google dengan Google Drive yang diaktifkan.

Menyiapkan lingkungan Anda

Untuk menyelesaikan panduan memulai ini, siapkan lingkungan Anda.

Mengaktifkan API

Sebelum menggunakan Google API, Anda harus mengaktifkannya di project Google Cloud. Anda dapat mengaktifkan satu atau beberapa API dalam satu project Google Cloud.

Mengizinkan kredensial untuk aplikasi desktop

Untuk mengautentikasi sebagai pengguna akhir dan mengakses data pengguna di aplikasi, Anda harus membuat satu atau beberapa Client ID OAuth 2.0. Client ID digunakan untuk mengidentifikasi satu aplikasi ke server OAuth Google. Jika aplikasi Anda berjalan di beberapa platform, Anda harus membuat client ID terpisah untuk setiap platform.
  1. Di Google Cloud Console, buka Menu > API & Layanan > Kredensial.

    Buka Kredensial

  2. Klik Create Credentials > OAuth client ID.
  3. Klik Jenis aplikasi > Aplikasi desktop.
  4. Di kolom Name, ketik nama untuk kredensial tersebut. Nama ini hanya ditampilkan di Google Cloud Console.
  5. Klik Create. Layar klien OAuth yang dibuat akan muncul, yang menunjukkan Client ID dan Rahasia klien baru Anda.
  6. Klik OK. Kredensial yang baru dibuat muncul di Client ID OAuth 2.0.
  7. Simpan file JSON yang didownload sebagai credentials.json, lalu pindahkan file ke direktori kerja Anda.

Menginstal library klien Google

  • Instal library klien Google untuk Python:

    pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
    

Mengonfigurasi contoh

  1. Dalam direktori kerja, buat file bernama quickstart.py.
  2. Sertakan kode berikut di quickstart.py:

    apps_script/quickstart/quickstart.py
    """
    Shows basic usage of the Apps Script API.
    Call the Apps Script API to create a new script project, upload a file to the
    project, and log the script's URL to the user.
    """
    from __future__ import print_function
    
    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient import errors
    from googleapiclient.discovery import build
    
    # If modifying these scopes, delete the file token.json.
    SCOPES = ['https://www.googleapis.com/auth/script.projects']
    
    SAMPLE_CODE = '''
    function helloWorld() {
      console.log("Hello, world!");
    }
    '''.strip()
    
    SAMPLE_MANIFEST = '''
    {
      "timeZone": "America/New_York",
      "exceptionLogging": "CLOUD"
    }
    '''.strip()
    
    
    def main():
        """Calls the Apps Script API.
        """
        creds = None
        # The file token.json stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.json'):
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.json', 'w') as token:
                token.write(creds.to_json())
    
        try:
            service = build('script', 'v1', credentials=creds)
    
            # Call the Apps Script API
            # Create a new project
            request = {'title': 'My Script'}
            response = service.projects().create(body=request).execute()
    
            # Upload two files to the project
            request = {
                'files': [{
                    'name': 'hello',
                    'type': 'SERVER_JS',
                    'source': SAMPLE_CODE
                }, {
                    'name': 'appsscript',
                    'type': 'JSON',
                    'source': SAMPLE_MANIFEST
                }]
            }
            response = service.projects().updateContent(
                body=request,
                scriptId=response['scriptId']).execute()
            print('https://script.google.com/d/' + response['scriptId'] + '/edit')
        except errors.HttpError as error:
            # The API encountered a problem.
            print(error.content)
    
    
    if __name__ == '__main__':
        main()

Menjalankan contoh

  1. Dalam direktori kerja Anda, buat dan jalankan contoh:

    python3 quickstart.py
    
  2. Saat pertama kali menjalankan contoh, Anda akan diminta untuk mengizinkan akses:

    1. Jika belum login ke Akun Google, Anda akan diminta untuk login. Jika Anda login ke beberapa akun, pilih satu akun yang akan digunakan untuk otorisasi.
    2. Klik Accept.

    Informasi otorisasi disimpan dalam sistem file sehingga saat berikutnya Anda menjalankan kode contoh, Anda tidak akan diminta untuk melakukan otorisasi.

Anda telah berhasil membuat aplikasi Python pertama yang membuat permintaan ke Google Apps Script API.

Langkah berikutnya