Home/Google App Script

Google App Script

Published On: 9 July 2021.By .
  • Product & platform Engineering

What is Google App script

Google app script is an application development platform on which we can build an app to interact with google workspace. It is the fastest and most reliable way to connect with google apps like Spreadsheet, Calendar, Drive, Gmail etc. Google itself provides the code editor and uses GCP to run your script. We just need few clicks and anyone can access the app globally through API Key. Isn’t it amazing ?

Writing your first Hello world app in App Script

App script is very similar to javascript. We can use few prebuilt libraries, provided by google to interact with google workspace and booom!! It’s done. Follow the steps to write your first app script :

1. Go to script.google.com and tab on New Project to create your new project.

 

 

2. Now you can see a Code.gs file where we can write our code. Delete the default code and paste the below code to the Code.gs file.

function createAndSendDocument() {
    // Create a new Google Doc named 'Hello, world!'
    var doc = DocumentApp.create('Hello, world!');

    // Access the body of the document, then add a paragraph.
    doc.getBody().appendParagraph('This document was created by Google Apps Script.');

    // Get the URL of the document.
    var url = doc.getUrl();

    // Get the email address of the active user - that's you.
    var email = Session.getActiveUser().getEmail();

    // Get the name of the document to use as an email subject line.
    var subject = doc.getName();

    // Append a new string to the "url" variable to use as an email body.
    var body = 'Link to your doc: ' + url;

    // Send yourself an email with a link to the document.
    GmailApp.sendEmail(email, subject, body);
}

 

The above code creates a google doc and sends an email to the current user with a link to the doc.

3. Now click on the save button to save the project and run the app in the editor mode. Do authenticate your google mail as it is required by app script to access the google app associated with that.

Hope you have run the script successfully. Nice going 🙂

Deploying the project

Till now we have written a chunk of code and successfully ran it but to make it accessible as an api, we have to deploy it and it is so damn easy. Once deployed, we can use the credentials to run this app globally in different programming languages like Go, Java, Node.js, PHP, Python, Ruby etc. Follow the below steps :

1. Just click on the Deploy button(top right corner).
2. Click on New deployment and select app type, for ex Web app.
3. Add a neat and self explainable description to it and click on deploy.

4. Copy the Deployment ID, as it would be required to run the script from python code.

Using the app script as a rest api in python

Once deployed, we can use the credentials to run this app locally in different programming languages like Go, Java, Node.js, PHP, Python, Ruby etc. In this example, I am running the app with python code.
Follow the below steps :
1. Create the Google Cloud Platform project with API enabled.
Refer to https://developers.google.com/workspace/guides/create-project

2. Create authorization credentials for a desktop application with API enabled.
Refer to https://developers.google.com/workspace/guides/create-project

3. Install the Google client library :

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

 

4. Create a quickstart.py file, paste the below code and run.

import os.path
from googleapiclient import errors
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.external_request', 'https://www.googleapis.com/auth/documents', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.labels']

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) #change the port according to the google auth credentials
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('script', 'v1', credentials=creds)

    # Call the Apps Script API
    try:
        # paste deployment id of your app script here
        API_ID = "AKfycbxv6tpqJ5_bmUBEQ7N91i8RiLxojj9hvHvzgXM-o430hCmUcPq54Cb8h_39ClINgoAD"

        request = {"function": "createAndSendDocument"}

        response = service.scripts().run(body=request, scriptId=API_ID).execute()

        return True
    except errors.HttpError as error:
        # The API encountered a problem.
        print(error.content)
        return False

if __name__ == '__main__':
    if main():
        print("Script ran successfully")
    else:
        print("An error occurred")

5. Hope you are good to go towards leaning more about Google App Script and GCP. Here are few recommended links for you.

Recommended links

https://developers.google.com/apps-script/articles/tutorials

https://github.com/googleworkspace/python-samples/tree/master/apps_script/quickstart

https://www.aurigait.com/blog/google-sheets-api-with-python

Enjoy leaning 😉

Related content

We Love Conversations

Say Hello
Go to Top