양식 또는 퀴즈 만들기

이 페이지에서는 양식과 관련된 이러한 작업을 수행하는 방법을 설명합니다.

  • 새 양식 만들기
  • 기존 양식 복사
  • 양식을 퀴즈로 변환하기

시작하기 전에

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

  • 얼리 어답터 프로그램 안내에 따라 승인/인증 및 사용자 인증 정보 설정을 완료합니다.
  • Forms API 개요를 읽어보세요.

새 양식 만들기

양식을 처음 만들 때는 제목 필드만 필요하며 요청의 다른 필드는 모두 무시됩니다. 양식의 콘텐츠와 메타데이터를 작성하거나 업데이트하려면 batchUpdate() 메서드를 사용합니다. 자세한 내용은 양식 또는 퀴즈 업데이트를 참조하세요.

REST

제목만 사용하여 forms.create() 메서드를 호출합니다.

샘플 요청 본문

{
  "info": {
      "title": "My new form"
  }
}

Python

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

Node.js

forms/snippets/create_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 in Node',
    },
  };
  const res = await forms.forms.create({
    requestBody: newForm,
  });
  console.log(res.data);
  return res.data;
}

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

기존 양식 복사

기존 양식을 Google Drive API로 복제하면 콘텐츠를 더 쉽게 재사용할 수 있습니다. Google Forms URL에서 양식 ID를 찾을 수 있습니다.

https://docs.google.com/forms/d/FORM_ID/edit

REST

복사하려는 양식의 ID를 사용하여 Google Drive API의 files.copy() 메서드를 호출합니다.

Python

form/snippets/duplicate_form.py
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"]


def main():
  """Shows copy file example in Drive v3 API.
  Prints the name, id and other data of the copied file.
  """
  creds = None
  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(
          "client_secrets.json", SCOPES
      )
      creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open("token.json", "w") as token:
      token.write(creds.to_json())

  service = build("drive", "v3", credentials=creds)

  # Call the Drive v3 API
  origin_file_id = "1ox-6vHFeKpC6mon-tL5ygBC8zpbTnTp76JCZdIg80hA"  # example ID
  copied_file = {"title": "my_copy"}
  results = (
      service.files().copy(fileId=origin_file_id, body=copied_file).execute()
  )
  print(results)


if __name__ == "__main__":
  main()

양식을 퀴즈로 변환하기

퀴즈를 만들려면 먼저 위에서 설명한 대로 양식을 만든 후 양식의 설정을 업데이트합니다. 업데이트하려면 양식 ID가 필요합니다.

REST

기존 양식에서 batch.update() 메서드를 호출하여 isQuiz 설정을 true로 설정합니다.

샘플 요청 본문

{
  "requests": [
    {
      "updateSettings": {
        "settings": {
          "quizSettings": {
            "isQuiz": True
          }
        },
       "updateMask": "quizSettings.isQuiz"
      }
    }
  ]
}

Python

forms/snippets/convert_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": "My new quiz",
    }
}

# Creates the initial form
result = form_service.forms().create(body=form).execute()

# JSON to convert the form into a quiz
update = {
    "requests": [
        {
            "updateSettings": {
                "settings": {"quizSettings": {"isQuiz": True}},
                "updateMask": "quizSettings.isQuiz",
            }
        }
    ]
}

# Converts the form into a quiz
question_setting = (
    form_service.forms()
    .batchUpdate(formId=result["formId"], body=update)
    .execute()
)

# Print the result to see it's now a quiz
getresult = form_service.forms().get(formId=result["formId"]).execute()
print(getresult)

Node.js

forms/snippets/convert_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 convert form to a quiz
  const updateRequest = {
    requests: [
      {
        updateSettings: {
          settings: {
            quizSettings: {
              isQuiz: true,
            },
          },
          updateMask: 'quizSettings.isQuiz',
        },
      },
    ],
  };
  const res = await forms.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: updateRequest,
  });
  console.log(res.data);
  return res.data;
}

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

다음 단계

다음 단계를 시도해 보세요.