API 调用方可通过字段掩码列出请求应返回或更新的字段。使用 FieldMask 可以使 API 避免不必要的工作,从而提高性能。Google 文档 API 中的读取和更新方法会使用字段掩码。
使用字段掩码进行读取
文档可能很大,并且通常情况下,您不需要读取请求返回的 Document
资源的每个部分。您可以使用 fields
网址参数限制 Docs API 响应中返回的内容。为获得最佳性能,请在回复中仅明确列出您需要的字段。
字段参数的格式与 FieldMask 的 JSON 编码相同。简而言之,多个不同字段用英文逗号分隔,子字段用英文句点分隔。字段名称可以在 camelCase 或 specified_by_underscores 中指定。为方便起见,可在括号中列出多个相同类型的子字段。
以下 documents.get
请求示例使用 title,body.content(paragraph),revisionId
字段掩码来提取文档的 title
、Body
对象的 Paragraph
以及文档中该文档的 revisionId
:
GET https://docs.googleapis.com/v1/documents/documentId?fields=title,body.content(paragraph),revisionId
对此方法调用的响应是一个 Document
对象,其中包含字段掩码中请求的组成部分:
{ "title": ""TITLE
", "body": { "content": [ {}, { "paragraph": { "elements": [ { "startIndex": 1, "endIndex": 59, "textRun": { "content": ""CONTENT
", "textStyle": {} } } ], "paragraphStyle": { "namedStyleType": "NORMAL_TEXT", "direction": "LEFT_TO_RIGHT" } } } ] }, "revisionId": "REVISION_ID
" }
使用字段掩码进行更新
有时,您只需要更新对象中的某些字段,而其他字段保持不变。documents.batchUpdate
操作中的更新请求使用字段掩码来告知 API 正在更改哪些字段。更新请求会忽略未在字段掩码中指定的任何字段,而是保留其当前值。
您还可以取消设置某个字段,方法是在更新的消息中不指定该字段,但将该字段添加到掩码中。此操作会清除该字段先前具有的任何值。
更新字段掩码的语法与读取字段掩码的语法相同。
以下示例使用 UpdateTextStyleRequest
在 range
5-20 中将文档中“GoogleDocs API”一词的样式设为粗体:
POST https://docs.googleapis.com/v1/documents/documentId:batchUpdate
{ "title": "TITLE
", "body": { "content": [ { "endIndex": 1, "sectionBreak": { "sectionStyle": { "columnSeparatorStyle": "NONE", "contentDirection": "LEFT_TO_RIGHT", "sectionType": "CONTINUOUS" } } }, { "startIndex": 1, "endIndex": 59, "paragraph": { "elements": [ { "startIndex": 1, "endIndex": 5, "textRun": { "content": "CONTENT
", "textStyle": {} } }, { "startIndex": 5, "endIndex": 20, "textRun": { "content": "CONTENT
", "textStyle": { "bold": true } } }, { "startIndex": 20, "endIndex": 59, "textRun": { "content": "CONTENT
", "textStyle": {} } } ], "paragraphStyle": { "namedStyleType": "NORMAL_TEXT", "direction": "LEFT_TO_RIGHT" } } } ] }, { ... // style details }, "revisionId": "REVISION_ID
", "suggestionsViewMode": "SUGGESTIONS_INLINE", "documentId": "DOCUMENT_ID
" }