Best practices for best results

There are several principles you should follow when using the Google Docs API. These include:

  • Edit backwards for efficiency
  • Plan for collaboration
  • Ensure state consistency with WriteControl

The following sections explain these principles.

Edit backwards for efficiency

Within a single call to the BatchUpdate method, order your requests in descending order of index location. This eliminates the need to calculate the index changes due to insertions and deletions.

Plan for collaboration

Expect the document state to change. Between one method call and another, other collaborators might update the document, as shown in the following diagram:

How a document can change between method calls.

This can lead to errors if your indexes are wrong. With multiple users editing a document using the UI, Google Docs takes care of this transparently, but as an API client your app must manage this. Even if you don't anticipate collaboration on the document, it's important to program defensively and make sure the document state remains consistent. For one way to ensure consistency, review the WriteControl section below.

Ensure state consistency with WriteControl

When you read and then update a document, you can make sure the document hasn't been updated by using the WriteControl field in the BatchUpdate method. This lets you make edits to the doc only if the version has not changed. Here's how you use it:

  1. Get the document and save the revisionId string that's included in it.
  2. Compose your update requests.
  3. Include a WriteControl object with the requiredRevisionId set to the string you saved.
  4. When you call BatchUpdate, if the document revision has changed it returns an error and doesn't perform an update.