google-docs-api

How do you create a document in Google Docs programmatically?


The documentation for Google Documents List API, seems to say that you can create a local document and upload it. Is there no way to actually create and edit a document on Google Docs through an API?


Solution

  • While the docs call it "uploading", everything boils down to sending an appropriately formatted HTTP POST request, so of course it can actually be a new creation rather than an actual "upload" of an otherwise existing file. (Creation through POST requests is similar to what's normally described as a REST API, though in real REST you'd typically use a PUT request instead of course).

    You just need to create a blob of data representing your document in any of the formats listed here -- depending on your programming language, simplest may be text/csv for a spreadsheet and application/rtf for a text-document -- then put in in an appropriately formatted POST data. For example, to make a spreadsheet in the simplest way (no metadata), you could POST something like:

    POST /feeds/default/private/full HTTP/1.1
    Host: docs.google.com
    GData-Version: 3.0
    Authorization: <your authorization header here>
    Content-Length: 81047
    Content-Type: text/csv
    Slug: Example Spreadsheet
    
    ColumnA, ColumnB
    23, 45
    

    Each specific programming language for which a dedicated API is supplied may offer help with this not-so-hard task; for example, in Python, per the docs, the API recommends using ETags to avoid overwriting changes when multiple clients are simultaneously "uploading" (i.e., creating or updating docs). But preparing the POST directly is always possible, since the almost-REST API is documented as the protocol underlying all language-specific APIs.