양식 또는 퀴즈 업데이트

양식에 콘텐츠를 추가하거나 설정, 메타데이터 또는 콘텐츠를 업데이트하려면 batchUpdate() 메서드를 사용하세요. 이 메서드는 변경사항을 일괄적으로 그룹화하므로 하나의 요청이 실패하면 다른 (잠재적으로 종속된) 변경사항이 작성되지 않습니다.

batchUpdate() 메서드는 응답 본문을 반환하며, 이 본문에는 각 요청에 대한 응답이 포함됩니다. 각 응답은 해당 요청과 동일한 색인을 차지합니다. 적용 가능한 응답이 없는 요청의 경우 해당 색인의 응답이 비어 있습니다.

시작하기 전에

이 페이지의 작업을 계속 진행하기 전에 다음 작업을 수행하세요.

  • 사전 체험 프로그램 안내에 따라 승인/인증 및 사용자 인증 정보 설정을 완료합니다.

메타데이터, 설정 또는 항목 업데이트

다음 예에서는 양식의 메타데이터를 업데이트하는 방법을 보여주지만 콘텐츠와 설정의 구조는 동일합니다. updateFormInfo 대신 updateItem 또는 updateSettings 요청을 사용합니다. 각 요청에 대해 변경할 필드의 이름과 업데이트된 값, 그리고 변경사항을 지정된 필드로 제한하는 updateMask 값을 제공합니다.

REST

양식의 설명을 업데이트하려면 양식 ID와 업데이트된 설명 값으로 batchUpdate() 메서드를 호출합니다.

샘플 요청 본문

    "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
import path from 'path';
import {forms} from '@googleapis/forms';
import {authenticate} from '@google-cloud/local-auth';

async function updateForm() {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await formsClient.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 formsClient.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });
  console.log(res.data);
  return res.data;
}

항목 추가

다음 예에서는 양식에 새 콘텐츠를 추가하는 방법을 보여줍니다. 새 콘텐츠를 추가할 때는 새 콘텐츠를 삽입해야 하는 색인이 있는 위치를 제공해야 합니다. 예를 들어 색인이 0인 위치는 양식 시작 부분에 콘텐츠를 삽입합니다.

REST

양식에 항목을 추가하려면 양식 ID와 항목의 정보 및 원하는 위치를 사용하여 batchUpdate() 메서드를 호출합니다.

샘플 요청 본문

"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
import path from 'path';
import {forms} from '@googleapis/forms';
import {authenticate} from '@google-cloud/local-auth';

async function addItem() {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await formsClient.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 formsClient.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });
  console.log(updateResponse.data);
  return updateResponse.data;
}

주문 요청

batchUpdate() 메서드는 createItem, updateItem과 같은 하위 요청 배열을 허용합니다. 하위 요청은 제공된 순서대로 한 번에 하나씩 검증됩니다.

예: batchUpdate 요청에 createItem 하위 요청이 두 개 있는 requests 배열이 있습니다. 하위 요청 A에는 location.index 0이 있고 하위 요청 B에는 location.index 1이 있습니다. requests 배열이 [A, B]인 경우 batchUpdate가 성공합니다. 배열이 [B, A]인 경우 batchUpdate이 실패합니다. 양식에 이미 색인 0의 항목이 포함되어 있지 않으면 location.index 1이 유효하지 않기 때문입니다.