pythongoogle-formsgoogle-forms-api

How to delete Questions from an already existing google form using API & Python


I have connect to the google form API using python. I was able to create a form with the questions I want. I am now trying to delete certain questions that have the word "Location" in the question title. I am having trouble doing this. I keep getting the below error:

Delete Requests: [{'itemId': '694f1da7'}, {'itemId': '71bc64d4'}, {'itemId': '4e41b483'}, {'itemId': '0e213f54'}, {'itemId': '6317804d'}, {'itemId': '63b56594'}, {'itemId': '3f950e5c'}, {'itemId': '4da4f659'}, {'itemId': '7b1d6335'}, {'itemId': '4f8ebf91'}, {'itemId': '41a10b4d'}, {'itemId': '32f9b1e8'}, {'itemId': '7e0e35eb'}, {'itemId': '4d1cbb79'}, {'itemId': '72945c2c'}, {'itemId': '1fe45ba1'}]
Error during delete operation: <HttpError 400 when requesting https://forms.googleapis.com/v1/forms/1g3dWknRPyyt7Dap46Bmo3IMAuNfz_12_uURJNzRyrWk:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "itemId" at 'requests[0]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[1]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[2]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[3]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[4]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[5]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[6]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[7]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[8]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[9]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[10]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[11]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[12]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[13]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[14]': Cannot find field.
Invalid JSON payload received. Unknown name "itemId" at 'requests[15]': Cannot find field.". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'requests[0]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[0]\': Cannot find field.'}, {'field': 'requests[1]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[1]\': Cannot find field.'}, {'field': 'requests[2]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[2]\': Cannot find field.'}, {'field': 'requests[3]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[3]\': Cannot find field.'}, {'field': 'requests[4]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[4]\': Cannot find field.'}, {'field': 'requests[5]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[5]\': Cannot find field.'}, {'field': 'requests[6]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[6]\': Cannot find field.'}, {'field': 'requests[7]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[7]\': Cannot find field.'}, {'field': 'requests[8]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[8]\': Cannot find field.'}, {'field': 'requests[9]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[9]\': Cannot find field.'}, {'field': 'requests[10]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[10]\': Cannot find field.'}, {'field': 'requests[11]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[11]\': Cannot find field.'}, {'field': 'requests[12]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[12]\': Cannot find field.'}, {'field': 'requests[13]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[13]\': Cannot find field.'}, {'field': 'requests[14]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[14]\': Cannot find field.'}, {'field': 'requests[15]', 'description': 'Invalid JSON payload received. Unknown name "itemId" at \'requests[15]\': Cannot find field.'}]}]">

Here is the code that I am using to delete the questions with the word 'Location' in them.

from googleapiclient.discovery import build
from google.oauth2 import service_account
from googleapiclient import discovery
import requests
import time
import os

#NFL Libraries

import nfl_data_py as nfldt

os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

# Replace with your service account credentials JSON file path
SERVICE_ACCOUNT_FILE = 'credentials.json'

# Replace with your Google Form ID
FORM_ID = 'Insert Form ID Here'

# Define the scopes for Google Forms API
SCOPES = ['https://www.googleapis.com/auth/forms', 'https://www.googleapis.com/auth/forms.body', "https://www.googleapis.com/auth/drive"]

# Authenticate and create the service
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
form_service = discovery.build(
    'forms', 'v1',
    credentials=credentials,
    discoveryServiceUrl='https://forms.googleapis.com/$discovery/rest?version=v1',
    static_discovery=False
)

# Retrieve the current form metadata
form_metadata = form_service.forms().get(formId=FORM_ID).execute()
print(form_metadata)

def delete_questions_with_location_in_title(FORM_ID):
    try:
        # Fetch form metadata to get all items
        form_metadata = form_service.forms().get(formId=FORM_ID).execute()
        items = form_metadata.get('items', [])

        # Prepare a list to hold the delete requests
        delete_requests = []

        # Iterate over the items and find the ones to delete
        for item in items:
            if 'title' in item and 'questionItem' in item:
                if 'Location' in item['title']:
                    item_id = item['itemId']
                    delete_requests.append({
                        "deleteItem": {
                            'itemId': item_id #I THINK THE ERROR IS HERE
                        }
                    })

        # Print the delete requests for debugging
        print(f"Delete Requests: {delete_requests}")

        # Execute the batch update if there are delete requests
        if delete_requests:
            batch_delete_request = {
                "requests": delete_requests
            }
            response = form_service.forms().batchUpdate(formId=FORM_ID, body=batch_delete_request).execute()
            print(f"Deleted {len(delete_requests)} questions from the form.")
            print(response)  # Print the response for debugging
        else:
            print("No items with 'Location' in title found for deletion.")
    
    except Exception as e:
        print(f"Error during delete operation: {e}")

# Call the function to delete questions with 'Location' in title
delete_questions_with_location_in_title(FORM_ID)

As I said, after i run this, i get the error i pasted above. I am not sure why. I think the error is in the 'itemID': item_id part.


Solution

  • Modification points:

    When this is reflected in your script, please modify it as follows.

    From:

    for item in items:
        if 'title' in item and 'questionItem' in item:
            if 'Location' in item['title']:
                item_id = item['itemId']
                delete_requests.append({
                    "deleteItem": {
                        'itemId': item_id #I THINK THE ERROR IS HERE
                    }
                })
    

    To:

    for idx, item in enumerate(items):
        if 'title' in item and 'questionItem' in item:
            if 'Location' in item['title']:
                item_id = item['itemId']
                delete_requests.append({"deleteItem": {"location": {"index": idx}}})
    delete_requests.reverse()
    

    Reference: