Aggiornare un modulo o un quiz

Per aggiungere contenuti a un modulo o aggiornare impostazioni, metadati o contenuti, utilizza il metodo batchUpdate(), che raggruppa le modifiche in un batch in modo che se una richiesta non va a buon fine, nessuna delle altre modifiche (potenzialmente dipendenti) venga scritta.

Il metodo batchUpdate() restituisce un corpo della risposta, all'interno del quale è presente una risposta per ogni richiesta. Ogni risposta occupa lo stesso indice della richiesta corrispondente; per le richieste senza risposta applicabile, la risposta all'indice sarà vuota.

Prima di iniziare

Prima di proseguire con le attività in questa pagina, esegui le seguenti operazioni:

  • Completa la configurazione di autorizzazione/autenticazione e delle credenziali nelle istruzioni del programma per early adopter

Aggiornare metadati, impostazioni o elementi

L'esempio seguente mostra come aggiornare i metadati di un modulo, ma la struttura è la stessa per i contenuti e le impostazioni: vengono utilizzate le richieste updateItem o updateSettings invece di updateFormInfo. Per ogni richiesta, fornisci il nome del campo da modificare e il valore aggiornato, insieme a un valore updateMask per limitare le modifiche ai campi specificati.

REST

Per aggiornare la descrizione del modulo, chiama il metodo batchUpdate() con l'ID modulo e il valore della descrizione aggiornato.

Corpo della richiesta di esempio

    "requests": [{
        "updateFormInfo": {
            "info": {
                "description": "Please complete this quiz based on this week's readings for class."
            },
            "updateMask": "description"
        }
    }]

Python

forms/snippets/update_form.py
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()
)

# Print the result to see it now has a description
getresult = form_service.forms().get(formId=createResult["formId"]).execute()
print(getresult)

Node.js

forms/snippets/update_form.js
'use strict';

const path = require('path');
const google = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

async function runSample(query) {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const forms = google.forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await forms.forms.create({
    requestBody: newForm,
  });
  console.log('New formId was: ' + createResponse.data.formId);

  // Request body to add description to a Form
  const update = {
    requests: [
      {
        updateFormInfo: {
          info: {
            description:
              'Please complete this quiz based on this week\'s readings for class.',
          },
          updateMask: 'description',
        },
      },
    ],
  };
  const res = await forms.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });
  console.log(res.data);
  return res.data;
}

if (module === require.main) {
  runSample().catch(console.error);
}
module.exports = runSample;

Aggiungere un articolo

L'esempio seguente mostra come aggiungere nuovi contenuti a un modulo. Quando aggiungi nuovi contenuti, devi fornire una posizione con un indice in cui inserire i nuovi contenuti. Ad esempio, una posizione con indice 0 inserirà il contenuto all'inizio del modulo.

REST

Per aggiungere un elemento al modulo, chiama il metodo batchUpdate() con l'ID modulo, le informazioni dell'elemento e la posizione desiderata.

Corpo della richiesta di esempio

"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

forms/snippets/add_item.py
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()
)

# Print the result to see it now has a video
result = form_service.forms().get(formId=createResult["formId"]).execute()
print(result)

Node.js

forms/snippets/add_item.js
'use strict';

const path = require('path');
const google = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

async function runSample(query) {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const forms = google.forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await forms.forms.create({
    requestBody: newForm,
  });
  console.log('New formId was: ' + createResponse.data.formId);

  // Request body to add video item to a Form
  const 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,
          },
        },
      },
    ],
  };
  const updateResponse = await forms.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });
  console.log(updateResponse.data);
  return updateResponse.data;
}

if (module === require.main) {
  runSample().catch(console.error);
}
module.exports = runSample;

Richiedi ordine

Il metodo batchUpdate() accetta un array di richieste secondarie come createItem e updateItem. Le richieste secondarie vengono convalidate una alla volta nell'ordine in cui vengono fornite.

Esempio: una richiesta batchUpdate ha un array requests con due richieste secondarie createItem. La richiesta secondaria A ha location.index 0, mentre la richiesta secondaria B ha location.index 1. Se l'array requests è [A, B], batchUpdate è sufficiente. Se l'array è [B, A], batchUpdate non riuscirà, poiché location.index 1 non è valido a meno che il modulo non contenga già un elemento all'indice 0.