### Install Google Forms API Client Library for Python (Manual) Source: https://developers.google.com/workspace/forms/api/guides/libraries Manually install the Python client library by downloading, unpacking, and running the setup script. ```bash python setup.py install ``` -------------------------------- ### Install Google Forms API Client Library for Python (Setuptools) Source: https://developers.google.com/workspace/forms/api/guides/libraries Use Setuptools to install or upgrade the Google Forms API client library for Python. This is an alternative managed installation method. ```bash easy_install --upgrade google-api-python-client ``` -------------------------------- ### Run the Python Quickstart Script Source: https://developers.google.com/workspace/forms/api/guides/quickstarts-overview Executes the Python quickstart script. The first run will prompt for OAuth 2.0 authorization. ```bash python3 quickstart.py ``` -------------------------------- ### Install Google API Client Library for Python Source: https://developers.google.com/workspace/forms/api/guides/quickstarts-overview Installs the necessary Google client libraries for Python. Ensure you have Python 3 installed. ```bash python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib ``` -------------------------------- ### Install Google Forms API Client Library for Python (pip) Source: https://developers.google.com/workspace/forms/api/guides/libraries Use pip to install or upgrade the Google Forms API client library for Python. This is the preferred method for managed installation. ```bash pip install --upgrade google-api-python-client ``` -------------------------------- ### Install Google Forms API Client Gem (Ruby) Source: https://developers.google.com/workspace/forms/api/guides/libraries Install the Google Forms API client library gem using RubyGems. You might need to prepend 'sudo' depending on your system configuration. ```bash gem install google-api-client ``` -------------------------------- ### Example Full Resource Response Source: https://developers.google.com/workspace/forms/api/guides/performance A sample JSON response from a generic API, illustrating the structure and fields typically returned when no specific fields are requested. ```json { "kind": "demo", ... "items": [ { "title": "First title", "comment": "First comment.", "characteristics": { "length": "short", "accuracy": "high", "followers": ["Jo", "Will"], }, "status": "active", ... }, { "title": "Second title", "comment": "Second comment.", "characteristics": { "length": "long", "accuracy": "medium" "followers": [ ], }, "status": "pending", ... }, ... ] } ``` -------------------------------- ### Partial Response Example Source: https://developers.google.com/workspace/forms/api/guides/performance Use the `fields` parameter to specify which fields to return in the response. This reduces the amount of data transferred. The syntax is similar to XPath. ```HTTP https://www.googleapis.com/demo/v1?**fields=kind,items(title,characteristics/length)** ``` ```HTTP **200 OK** ``` ```JSON { "kind": "demo", "items": [{ "title": "First title", "characteristics": { "length": "short" } }, { "title": "Second title", "characteristics": { "length": "long" } }, ... ] } ``` -------------------------------- ### Example Partial Resource Response Source: https://developers.google.com/workspace/forms/api/guides/performance A sample JSON response after requesting specific fields using the 'fields' parameter. It contains only the 'kind' and specified 'items' fields. ```json { "kind": "demo", "items": [{ "title": "First title", "characteristics": { "length": "short" } }, { "title": "Second title", "characteristics": { "length": "long" } }, ... ] } ``` -------------------------------- ### Forms API Response Example Source: https://developers.google.com/workspace/forms/api/guides/apps-script-setup This is an example of a response received from the Forms API after executing a script. It shows the structure of form responses, including response IDs, timestamps, and answers to specific questions. ```json { "responses": [ { "responseId":"...", "createTime": "2021-03-25T01:23:58.146Z", "lastSubmittedTime": "2021-03-25T01:23:58.146607Z", "answers": { "1e9b0ead": { "questionId": "1e9b0ead", "textAnswers": { "answers": [ { "value": "Red" } ] } }, "773ed8f3": { "questionId": "773ed8f3", "textAnswers": { "answers": [ { "value": "Tesla" } ] } } } } ] } ``` -------------------------------- ### Python Quickstart for Google Forms API Source: https://developers.google.com/workspace/forms/api/guides/quickstarts-overview This script demonstrates how to authenticate with the Google Forms API, create a new form, add a multiple-choice question, and retrieve the form details. It requires `credentials.json` and `client_secrets.json` files in the working directory. ```python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/forms.body" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) creds = tools.run_flow(flow, store) form_service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) # Request body for creating a form NEW_FORM = { "info": { "title": "Quickstart form", } } # Request body to add a multiple-choice question NEW_QUESTION = { "requests": [ { "createItem": { "item": { "title": ( "In what year did the United States land a mission on" " the moon?" ), "questionItem": { "question": { "required": True, "choiceQuestion": { "type": "RADIO", "options": [ {"value": "1965"}, {"value": "1967"}, {"value": "1969"}, {"value": "1971"}, ], "shuffle": True, }, } }, }, "location": {"index": 0}, } } ] } # Creates the initial form result = form_service.forms().create(body=NEW_FORM).execute() # Adds the question to the form question_setting = ( form_service.forms() .batchUpdate(formId=result["formId"], body=NEW_QUESTION) .execute() ) # Prints the result to show the question has been added get_result = form_service.forms().get(formId=result["formId"]).execute() print(get_result) ``` -------------------------------- ### Google Drive API Authentication Setup (Python) Source: https://developers.google.com/workspace/forms/api/guides/publish-form Sets up the necessary scopes and file paths for Google Drive API authentication using OAuth 2.0. This code is typically used at the beginning of a script that interacts with Google Drive. ```python 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.discovery import build # If modifying these SCOPES, delete the file token.json. SCOPES = ["https://www.googleapis.com/auth/drive.file"] CLIENT_SECRET_FILE = "client_secrets.json" TOKEN_FILE = "token.json" ``` -------------------------------- ### Get Form Details Source: https://developers.google.com/workspace/forms/api/guides/update-form-quiz Retrieves the details of a specific form using its ID and prints the result. ```python result = form_service.forms().get(formId=createResult["formId"]).execute() print(result) ``` -------------------------------- ### Get Form Responders (Python) Source: https://developers.google.com/workspace/forms/api/guides/publish-form Retrieves a list of users who have access to respond to a published form. Requires authentication and the Drive API. ```python YOUR_FORM_ID = "YOUR_FORM_ID" def get_credentials(): """Gets the credentials for the user.""" creds = None if os.path.exists(TOKEN_FILE): creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES) 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( CLIENT_SECRET_FILE, SCOPES ) creds = flow.run_local_server(port=8080) with open(TOKEN_FILE, "w") as token: token.write(creds.to_json()) return creds def get_responders(): """Gets the responders for the form.""" creds = get_credentials() drive_service = build("drive", "v3", credentials=creds) try: response = ( drive_service.permissions() .list( fileId=YOUR_FORM_ID, fields="permissions(id,emailAddress,type,role,view)", includePermissionsForView="published", ) .execute() ) published_readers = [] for permission in response.get("permissions", []): # 'view': 'published' indicates it's related to the published link. # 'role': 'reader' is standard for responders. # 'type': 'user' for specific users, 'anyone' for public. if ( permission.get("view") == "published" and permission.get("role") == "reader" ): published_readers.append(permission) if published_readers: print("Responders for this form:") print(published_readers) else: print("No specific published readers found for this form.") except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": get_responders() ``` -------------------------------- ### Publish a Google Form (Node.js) Source: https://developers.google.com/workspace/forms/api/guides/publish-form This Node.js snippet demonstrates how to publish a Google Form and set it to accept responses. It uses the `@googleapis/forms` library and requires authentication setup. ```javascript import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; /** * Publishes a Google Form. * * @param {string} formIdToPublish The ID of the form to publish. */ async function publishForm(formIdToPublish) { // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); // The request body to publish the form and start accepting responses. const setPublishSettingsRequest = { publishSettings: { publishState: { isPublished: true, isAcceptingResponses: true, }, }, }; try { // Send the request to update the form's publish settings. const result = await formsClient.forms.setPublishSettings({ formId: formIdToPublish, requestBody: setPublishSettingsRequest, }); console.log('Form publish settings updated:', result.data); } catch (err) { console.error('Error setting publish settings:', err); } } ``` -------------------------------- ### Example Quiz JSON Structure Source: https://developers.google.com/workspace/forms/api/guides This JSON represents a sample quiz, including its title, description, settings, and individual items such as an image and multiple-choice questions. Use this structure as a reference when creating or managing forms programmatically. ```json { "formId": "FORM_ID", "info": { "title": "Famous Black Women", "description": "Please complete this quiz based off of this week's readings for class.", "documentTitle": "Famous Black Women" }, "settings": { "quizSettings": { "isQuiz": true } }, "revisionId": "00000021", "responderUri": "https://docs.google.com/forms/d/e/1FAIpQLSd0iBLPh4suZoGW938EU1WIxzObQv_jXto0nT2U8HH2KsI5dg/viewform", "items": [ { "itemId": "5d9f9786", "imageItem": { "image": { "contentUri": "DIRECT_URL", "properties": { "alignment": "LEFT" } } } }, { "itemId": "72b30353", "title": "Which African American woman authored \"I Know Why the Caged Bird Sings\"?", "questionItem": { "question": { "questionId": "25405d4e", "required": true, "grading": { "pointValue": 2, "correctAnswers": { "answers": [ { "value": "Maya Angelou" } ] } }, "choiceQuestion": { "type": "RADIO", "options": [ { "value": "Maya Angelou" }, { "value": "bell hooks" }, { "value": "Alice Walker" }, { "value": "Roxane Gay" } ] } } } }, { "itemId": "0a4859c8", "title": "Who was the first Dominican-American woman elected to state office?", "questionItem": { "question": { "questionId": "37fff47a", "grading": { "pointValue": 2, "correctAnswers": { "answers": [ { "value": "Grace Diaz" } ] } }, "choiceQuestion": { "type": "RADIO", "options": [ { "value": "Rosa Clemente" }, { "value": "Grace Diaz" }, { "value": "Juana Matias" }, { "value": "Sabrina Matos" } ] } } } } ], "publishSettings" : { "isPublished": true, "isAcceptingResponses": true } } ``` -------------------------------- ### Retrieve All Form Responses (Python) Source: https://developers.google.com/workspace/forms/api/guides/retrieve-forms-responses Use this Python code to fetch all responses submitted to a form. Ensure that the `forms.responses.readonly` scope is included in your authentication setup. ```python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/forms.responses.readonly" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) creds = tools.run_flow(flow, store) service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) ``` -------------------------------- ### Get All Form Responses (Python) Source: https://developers.google.com/workspace/forms/api/guides/retrieve-forms-responses Use this snippet to retrieve all responses for a specified form. Ensure you have authenticated and built the Forms API service. ```python form_id = "" result = service.forms().responses().list(formId=form_id).execute() print(result) ``` -------------------------------- ### Retrieve Form Contents and Metadata (Python) Source: https://developers.google.com/workspace/forms/api/guides/retrieve-forms-responses Use this snippet to get the content, settings, and metadata of a specific form. Ensure you have completed authentication and have your form ID. ```python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/forms.body.readonly" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) creds = tools.run_flow(flow, store) service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) # Prints the title of the sample form: form_id = "" result = service.forms().get(formId=form_id).execute() print(result) ``` -------------------------------- ### Update Google Forms API Client Gem (Ruby) Source: https://developers.google.com/workspace/forms/api/guides/libraries Update an existing installation of the Google Forms API client library gem to the latest version. ```bash gem update -y google-api-client ``` -------------------------------- ### Get Form Responders (Node.js) Source: https://developers.google.com/workspace/forms/api/guides/publish-form Retrieves a list of users who have access to respond to a published form using the Drive API. Requires authentication and the Drive API. ```javascript import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {drive} from '@googleapis/drive'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']; /** * Gets the responders of a form. * This is done by listing the permissions of the form in Google Drive. * * @param {string} formId The ID of the form. */ async function getResponders(formId) { // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); // Create a new Drive API client. const driveService = drive({version: 'v3', auth: authClient}); try { // List the permissions for the form. const result = await driveService.permissions.list({ fileId: formId, includePermissionsForView: 'published', fields: 'permissions(id,emailAddress,type,role,view)', }); const permissions = result.data.permissions || []; if (permissions.length === 0) { console.log(`No permissions found for form ID: ${formId}`); } else { console.log('Responders for this form:'); // A responder is a permission with view='published' and role='reader'. for (const permission of permissions) { if (permission.view === 'published' && permission.role === 'reader') { console.log(`Responder:`, permission); } } } } catch (err) { console.error('Error getting responders :', err); } } ``` -------------------------------- ### Request Full Resource Data (Default) Source: https://developers.google.com/workspace/forms/api/guides/performance This HTTP GET request to a generic API endpoint omits the 'fields' parameter, resulting in the server returning the complete resource representation. ```http https://www.googleapis.com/demo/v1 ``` -------------------------------- ### List Form Responses Source: https://developers.google.com/workspace/forms/api/reference/rest/v1/forms.responses/list To list form responses, use a `GET` request to the specified URL, including the form's ID in the path. Utilize optional query parameters like `filter`, `pageSize`, and `pageToken` to refine the results. The request body must be empty. The response includes an array of form responses and a `nextPageToken` if additional responses are available. Authorization requires specific OAuth scopes like `drive`, `drive.file`, or `forms.responses.readonly`. ```APIDOC ## GET /v1/forms/{formId}/responses ### Description Lists all responses for a specific Google Form. ### Method GET ### Endpoint `https://forms.googleapis.com/v1/forms/{formId}/responses` ### Parameters #### Path Parameters - **formId** (string) - Required. ID of the Form whose responses to list. #### Query Parameters - **filter** (string) - Optional. Filters the form responses. Supported format: `timestamp > _N_` or `timestamp >= _N_`, where _N_ is an RFC3339 UTC "Zulu" formatted timestamp. - **pageSize** (integer) - Optional. The maximum number of responses to return. Defaults to 5000 if not specified or zero. - **pageToken** (string) - Optional. A page token returned by a previous list response. Used to retrieve the next page of results. ### Request Body This endpoint does not accept a request body. ### Response #### Success Response (200) - **responses** (array of FormResponse) - The returned form responses. The `formId` field is not included in the `FormResponse` object for list requests. - **nextPageToken** (string) - If set, indicates that there are more responses available. Provide this token in a future request to get the next page. #### Response Example ```json { "responses": [ { "answers": {}, "createTime": "2023-01-01T12:00:00Z", "lastUpdateTime": "2023-01-01T12:05:00Z", "respondentEmail": "user@example.com" } ], "nextPageToken": "CAIQAg" } ``` ### Authorization Scopes - `https://www.googleapis.com/auth/drive` - `https://www.googleapis.com/auth/drive.file` - `https://www.googleapis.com/auth/forms.responses.readonly` ``` -------------------------------- ### Unpublish Form (Apps Script) Source: https://developers.google.com/workspace/forms/api/guides/publish-form Example of how to unpublish a Google Form using Apps Script. ```javascript /** * Unpublishes a Google Form using its URL. */ function unpublishMyForm() { // Replace with the URL of your Google Form const formUrl = 'https://docs.google.com/forms/d/YOUR_FORM_ID/edit'; try { const form = FormApp.openByUrl(formUrl); // Unpublish the form. This also disables accepting responses. form.setPublished(false); Logger.log(`Form "${form.getTitle()}" unpublished successfully.`); // Optional: Verify the state if (!form.isPublished()) { Logger.log('Form is now unpublished.'); } if (!form.isAcceptingResponses()) { Logger.log('Form is no longer accepting responses.'); } } catch (error) { Logger.log(`Error unpublishing form: ${error}`); } } ``` -------------------------------- ### forms.get Source: https://developers.google.com/workspace/forms/api/reference/rest/v1/forms/get Retrieves a Google Form by its ID. This operation allows you to get the details of a specific form. ```APIDOC ## GET https://forms.googleapis.com/v1/forms/{formId} ### Description Get a form. ### Method GET ### Endpoint https://forms.googleapis.com/v1/forms/{formId} ### Parameters #### Path Parameters - **formId** (string) - Required. The form ID. ### Request Body The request body must be empty. ### Response Body If successful, the response body contains an instance of `Form`. ### Authorization Scopes Requires one of the following OAuth scopes: - `https://www.googleapis.com/auth/drive` - `https://www.googleapis.com/auth/drive.file` - `https://www.googleapis.com/auth/drive.readonly` - `https://www.googleapis.com/auth/forms.body` - `https://www.googleapis.com/auth/forms.body.readonly` ``` -------------------------------- ### Get All Form Responses (Node.js) Source: https://developers.google.com/workspace/forms/api/guides/retrieve-forms-responses This Node.js function retrieves all responses from a form. It requires authentication and a valid form ID. ```javascript import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; // TODO: Replace with a valid form ID. const formID = ''; /** * Retrieves all responses from a form. */ async function getAllResponses() { // Authenticate with Google and get an authorized client. const auth = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/forms.responses.readonly', }); // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth, }); // Get the list of responses for the form. const result = await formsClient.forms.responses.list({ formId: formID, }); console.log(result.data); return result.data; } ``` -------------------------------- ### Sample Request Body for Permissions Create Source: https://developers.google.com/workspace/forms/api/guides/publish-form This is a sample JSON object representing the body for a `permissions.create` request to add a responder to a form. ```json { "view": "published", "role": "reader", "type": "user", "emailAddress": "user@example.com" } ``` -------------------------------- ### Python: Update form description Source: https://developers.google.com/workspace/forms/api/guides/update-form-quiz This Python snippet demonstrates how to authenticate, build the Forms API service, create an initial form, and then update its description using the batchUpdate method. ```python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/forms.body" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) creds = tools.run_flow(flow, store) form_service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) form = { "info": { "title": "Update metadata example for Forms API!", } } # Creates the initial Form createResult = form_service.forms().create(body=form).execute() # Request body to add description to a Form update = { "requests": [ { "updateFormInfo": { "info": { "description": ( "Please complete this quiz based on this week's" " readings for class." ) }, "updateMask": "description", } } ] } # Update the form with a description question_setting = ( form_service.forms() .batchUpdate(formId=createResult["formId"], body=update) .execute() ) ``` -------------------------------- ### Initialize Google Forms API Client Source: https://developers.google.com/workspace/forms/api/guides/publish-form This Python snippet sets up the necessary imports and constants for interacting with the Google Forms API, including authentication scopes and discovery document. ```python 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.discovery import build # If modifying these SCOPES, delete the file token.json. SCOPES = ["https://www.googleapis.com/auth/forms.body"] DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" CLIENT_SECRET_FILE = "client_secrets.json" TOKEN_FILE = "token.json" ``` -------------------------------- ### Update Form Description Source: https://developers.google.com/workspace/forms/api/guides/update-form-quiz This example demonstrates how to update the description of a Google Form using the batchUpdate method. The updateMask ensures only the description field is modified. ```APIDOC ## Update Form Description ### Description Updates the description of a Google Form. ### Method `batchUpdate` ### Endpoint `forms.batchUpdate` ### Parameters #### Path Parameters - **formId** (string) - Required - The ID of the form to update. #### Request Body - **requests** (array) - Required - A list of update requests. - **updateFormInfo** (object) - Required - Request to update form information. - **info** (object) - Required - The form information to update. - **description** (string) - Required - The new description for the form. - **updateMask** (string) - Required - Specifies which fields in `info` to update. Use "description" to update only the description. ### Request Example ```json { "requests": [ { "updateFormInfo": { "info": { "description": "Please complete this quiz based on this week's readings for class." }, "updateMask": "description" } } ] } ``` ### Response #### Success Response (200) - **replies** (array) - A list of replies, one for each request in the batch. The reply at each index corresponds to the request at the same index. For requests with no applicable response, the response at that index will be empty. #### Response Example ```json { "replies": [ { "updateFormInfo": { "formId": "12345abcde", "updatedFormInfo": { "description": "Please complete this quiz based on this week's readings for class." } } } ] } ``` ``` -------------------------------- ### Sample Request Body for SetPublishSettings Source: https://developers.google.com/workspace/forms/api/guides/publish-form This is a sample REST API request body for the `setPublishSettings` method, illustrating how to set both the published state and response acceptance status. ```json { "publishSettings": { "publishState": { "isPublished": true, "isAcceptingResponses": false } } } ``` -------------------------------- ### Set form to accept 'Anyone with link' responses (Python) Source: https://developers.google.com/workspace/forms/api/guides/publish-form This Python snippet configures a form to accept responses from anyone with the link. It requires the Drive service to be built and authenticated. ```python def set_anyone_with_link_responder(): """Sets anyone with the link to be a responder for the form.""" creds = get_credentials() drive_service = build("drive", "v3", credentials=creds) permission_body = { "type": "anyone", "view": "published", # Key for making it a responder setting "role": "reader", } try: response = ( ``` -------------------------------- ### Create a Watch for Form Responses (Node.js) Source: https://developers.google.com/workspace/forms/api/guides/push-notifications This Node.js snippet demonstrates how to create a watch on a Google Form to receive real-time notifications for new responses. It handles authentication using local credentials and specifies the Pub/Sub topic for delivery. Remember to replace placeholder values. ```Node.js import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; // TODO: Replace with a valid form ID. const formID = ''; /** * Creates a watch on a form to get notifications for new responses. */ async function createWatch() { // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); // The request body to create a watch. const watchRequest = { watch: { target: { topic: { // TODO: Replace with a valid Cloud Pub/Sub topic name. topicName: 'projects/', }, }, // The event type to watch for. 'RESPONSES' is the only supported type. eventType: 'RESPONSES', }, }; // Send the request to create the watch. const result = await formsClient.forms.watches.create({ formId: formID, requestBody: watchRequest, }); console.log(result.data); return result.data; } ``` -------------------------------- ### Enable Gzip Compression for API Requests Source: https://developers.google.com/workspace/forms/api/guides/performance To reduce bandwidth, set the 'Accept-Encoding' header to 'gzip' and include 'gzip' in your User-Agent string. This is beneficial for most API calls. ```http Accept-Encoding: gzip User-Agent: my program (gzip) ``` -------------------------------- ### Add a video item to a form Source: https://developers.google.com/workspace/forms/api/guides/update-form-quiz To add new content, such as a video, to a form, use the `batchUpdate` method with a `createItem` request. You must provide a `location` with an `index` to specify where the item should be inserted. ```json "requests": [{ "createItem": { "item": { "title": "Homework video", "description": "Quizzes in Google Forms", "videoItem": { "video": { "youtubeUri": "https://www.youtube.com/watch?v=Lt5HqPvM-eI" } }}, "location": { "index": 0 } }] ``` ```python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/forms.body" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) creds = tools.run_flow(flow, store) form_service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) form = { "info": { "title": "Update item example for Forms API", } } # Creates the initial Form createResult = form_service.forms().create(body=form).execute() # Request body to add a video item to a Form update = { "requests": [ { "createItem": { "item": { "title": "Homework video", "description": "Quizzes in Google Forms", "videoItem": { "video": { "youtubeUri": ( "https://www.youtube.com/watch?v=Lt5HqPvM-eI" ) } }, }, "location": {"index": 0}, } } ] } # Add the video to the form question_setting = form_service.forms () .batchUpdate(formId=createResult["formId"], body=update) .execute() ``` -------------------------------- ### Create a Watch for Form Responses (Python) Source: https://developers.google.com/workspace/forms/api/guides/push-notifications Use this snippet to create a watch on a Google Form to receive notifications for new responses. Ensure you have authenticated and built the Forms API service. Replace placeholders with your actual form ID and Cloud Pub/Sub topic path. ```Python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/drive" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secret.json", SCOPES) creds = tools.run_flow(flow, store) service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) watch = { "watch": { "target": {"topic": {"topicName": ""}}, "eventType": "RESPONSES", } } form_id = "" # Print JSON response after form watch creation result = service.forms().watches().create(formId=form_id, body=watch).execute() print(result) ``` -------------------------------- ### Retrieve Form Contents and Metadata (Node.js) Source: https://developers.google.com/workspace/forms/api/guides/retrieve-forms-responses This Node.js snippet retrieves the structure and settings of a Google Form. It requires authentication setup and a valid form ID. ```javascript import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; // TODO: Replace with a valid form ID. const formID = ''; /** * Retrieves the content of a form. */ async function getForm() { // Authenticate with Google and get an authorized client. const auth = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/forms.body.readonly', }); // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth, }); // Get the form content. const result = await formsClient.forms.get({formId: formID}); console.log(result.data); return result.data; } ``` -------------------------------- ### Retrieve a Single Form Response (Python) Source: https://developers.google.com/workspace/forms/api/guides/retrieve-forms-responses Use this snippet to get a specific response from your form using its ID. Ensure the Forms API service is built and authenticated. ```python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/forms.responses.readonly" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) creds = tools.run_flow(flow, store) service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) # Prints the specified response from your form: form_id = "" response_id = "" result = ( service.forms() .responses() .get(formId=form_id, responseId=response_id) .execute() ) print(result) ``` -------------------------------- ### Publish a Google Form (Python) Source: https://developers.google.com/workspace/forms/api/guides/publish-form Use this Python snippet to publish a Google Form and enable response acceptance. Ensure you have authenticated credentials and the correct Form ID. ```python # TODO: Replace with your Form ID YOUR_FORM_ID = "YOUR_ID" def get_credentials(): """Gets the credentials for the user.""" creds = None if os.path.exists(TOKEN_FILE): creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES) 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( CLIENT_SECRET_FILE, SCOPES) creds = flow.run_local_server(port=8080) with open(TOKEN_FILE, "w") as token: token.write(creds.to_json()) return creds def publish_form(): """Publishes the form.""" creds = get_credentials() form_service = build( "forms", "v1", credentials=creds, discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) # Request body for updating publish settings set_publish_settings_request = { "publishSettings": { "publishState": {"isPublished": True, "isAcceptingResponses": True} }, } try: response = ( form_service.forms() .setPublishSettings( formId=YOUR_FORM_ID, body=set_publish_settings_request ) .execute() ) print(f"Form {YOUR_FORM_ID} publish settings updated: {response}") except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": publish_form() ``` ``` -------------------------------- ### Stop Accepting Responses for a Form (Node.js) Source: https://developers.google.com/workspace/forms/api/guides/publish-form This Node.js snippet demonstrates how to prevent a Google Form from accepting new responses. It requires authentication setup and the form ID. ```javascript import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json'); const SCOPES = 'https://www.googleapis.com/auth/forms.body'; /** * Stops a form from accepting new responses. * * @param {string} formId The ID of the form. */ async function stopAcceptingResponses(formId) { // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: CREDENTIALS_PATH, scopes: SCOPES, }); // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); // The request body to stop accepting responses. const setPublishSettingsRequest = { publishSettings: { publishState: { isPublished: true, // Keep the form published. isAcceptingResponses: false, // Stop accepting new responses. }, }, }; try { // Send the request to update the form's settings. const res = await formsClient.forms.setPublishSettings({ formId, requestBody: setPublishSettingsRequest, }); console.log('Form is no longer accepting responses.', res.data); } catch (err) { console.error('Error setting publish settings:', err); } } ``` -------------------------------- ### Set Anyone with Link as Responder (Python) Source: https://developers.google.com/workspace/forms/api/guides/publish-form Grants 'anyone with the link' the ability to respond to a Google Form by creating a specific Drive API permission. Ensure you have the form ID and necessary authentication. ```python def set_anyone_with_link_responder(YOUR_FORM_ID): """Sets anyone with the link to be a responder for the form.""" creds = get_credentials() drive_service = build("drive", "v3", credentials=creds) permission_body = { "type": "anyone", "role": "reader", "view": "published", } try: response = ( drive_service.permissions() .create( fileId=YOUR_FORM_ID, body=permission_body, ) .execute() ) print( "'Anyone with the link can respond' permission set for form" f" {YOUR_FORM_ID}: {response}" ) return True except Exception as e: print(f"An error occurred: {e}") return False ``` -------------------------------- ### Create a New Google Form using Python Source: https://developers.google.com/workspace/forms/api/guides/create-form-quiz This Python snippet demonstrates how to authenticate and use the Forms API to create a new form with a specified title. ```python from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/drive" DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1" store = file.Storage("token.json") creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES) creds = tools.run_flow(flow, store) form_service = discovery.build( "forms", "v1", http=creds.authorize(Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False, ) form = { "info": { "title": "My new form", }, } # Prints the details of the sample form result = form_service.forms().create(body=form).execute() print(result) ``` -------------------------------- ### Request Specific Fields for Partial Response Source: https://developers.google.com/workspace/forms/api/guides/performance Use the 'fields' parameter in your HTTP GET request to specify only the desired fields, significantly reducing the amount of data transferred and processed. ```http https://www.googleapis.com/demo/v1?**fields=kind,items(title,characteristics/length)** ``` -------------------------------- ### Add grading options to a new question Source: https://developers.google.com/workspace/forms/api/guides/setup-grading Sample JSON code for a new question item that includes grading options. This allows for setting point values, correct answers, and feedback for right or wrong responses. ```json "item": { "title": "Which of these singers was not a member of Destiny's Child?", "questionItem": { "question": { "required": true, "grading": { "pointValue": 2, "correctAnswers": { "answers": [{"value": "Rihanna"}] }, "whenRight": {"text": "You got it!"}, "whenWrong": {"text": "Sorry, that's wrong"} }, "choiceQuestion": { "type": "RADIO", "options": [ {"value": "Kelly Rowland"}, {"value": "Beyoncé"}, {"value": "Rihanna"}, {"value": "Michelle Williams"} ] } } } } ``` -------------------------------- ### Convert a form to a quiz using Node.js Source: https://developers.google.com/workspace/forms/api/guides/create-form-quiz This Node.js snippet shows how to create a form and then convert it into a quiz using the Forms API. It utilizes the @googleapis/forms client library and the batchUpdate method for conversion. ```javascript import path from 'node:path'; import {authenticate} from '@google-cloud/local-auth'; import {forms} from '@googleapis/forms'; /** * Creates a new form and then converts it into a quiz. */ async function convertForm() { // Authenticate with Google and get an authorized client. const authClient = await authenticate({ keyfilePath: path.join(__dirname, 'credentials.json'), scopes: 'https://www.googleapis.com/auth/drive', }); // Create a new Forms API client. const formsClient = forms({ version: 'v1', auth: authClient, }); // The initial form to be created. const newForm = { info: { title: 'Creating a new form for batchUpdate in Node', }, }; // Create the new form. const createResponse = await formsClient.forms.create({ requestBody: newForm, }); if (!createResponse.data.formId) { throw new Error('Failed to create form.'); } console.log(`New formId was: ${createResponse.data.formId}`); // Request body to convert the form to a quiz. const updateRequest = { requests: [ { updateSettings: { settings: { quizSettings: { isQuiz: true, }, }, // The updateMask specifies which fields to update. updateMask: 'quizSettings.isQuiz', }, }, ], }; // Send the batch update request to convert the form to a quiz. const result = await formsClient.forms.batchUpdate({ formId: createResponse.data.formId, requestBody: updateRequest, }); console.log(result.data); return result.data; } ``` -------------------------------- ### Create a Form Watch Source: https://developers.google.com/workspace/forms/api/reference/rest/v1/forms.watches/create Send a POST request to create a watch for a specific form. Include the form ID in the URL and provide a watch object and an optional watch ID in the request body. Ensure the watch ID meets the specified character and format requirements. ```HTTP POST https://forms.googleapis.com/v1/forms/{formId}/watches ``` -------------------------------- ### Get OAuth Access Token in Apps Script Source: https://developers.google.com/workspace/forms/api/guides/apps-script-example Obtain a scoped and authenticated OAuth access token within an Apps Script project. This token is required for making authenticated REST calls to the Forms API. ```javascript ScriptApp.getOAuthToken(); ```