Working with Python and Google Docs API for Document Management

I’m working on a Python project that uses the Google Docs API to manage documents and folders. I’m pretty new to Python so I could use some guidance.

What I want to accomplish:

  1. Check if a folder called [My Folder] already exists, and create it only if it doesn’t
  2. Add new documents inside [My Folder]
  3. Get a complete list of all documents from [My Folder] with their direct links

I’m working with Google Docs API 3.0 and using gdata-2.0.16 library for Python.

Current code:

import gdata.docs.data
import gdata.docs.client

class AppConfig(object):
    APPLICATION_NAME = 'MyDocumentManager-v1.0'
    DEBUG_MODE = False

docs_client = gdata.docs.client.DocsClient()
docs_client.ClientLogin('[my_email]','[my_password]',source=AppConfig.APPLICATION_NAME)

folder = gdata.docs.data.Resource(type='folder', title='My Folder')
folder = docs_client.CreateResource(folder)

new_doc = gdata.docs.data.Resource(type='document', title='My New Document')
new_doc = docs_client.CreateResource(new_doc, collection=folder)

Where I’m stuck:

  1. How can I verify if [My Folder] already exists before creating it?
  2. What’s the best way to fetch contents from a specific folder only?
  3. How do I extract the full URLs for documents I’ve created in this folder?

I know my code needs work but any tips would be really helpful. Thanks!

Had the same problems when I started with Google APIs. To check if a folder exists, grab all resources with GetResources() and loop through them. Look for resource.resource_type == 'folder' and resource.title.text == 'My Folder'. Save the folder reference if you find it, create one if you don’t. Fair warning - folder operations are painfully slow. Cache those folder IDs if you’re hitting this often. For document URLs, GetAlternateLink() gets you sharing links. Need edit URLs? Hunt for links with rel='edit' in the entry data. Here’s something that bit me: new documents don’t show up in folder listings right away. Throw in a small delay if you’re querying immediately after creating stuff.

hey, just a heads up - gdata is kinda outdated. google shifted to the new google-api-python-client ages ago. it’s got way better docs and support, plus gdata might not work soon. consider upgrading!

Your code has a few fixable issues. To check if a folder exists, query all resources first then filter by title and type. Use docs_client.GetResources() and loop through to find folders named ‘My Folder’. For folder contents, add the collection parameter: docs_client.GetResources(uri=folder.GetSelfLink().href + '/contents'). Getting URLs is easy - each document has a GetAlternateLink() method that gives you the viewable link. That said, gdata’s deprecated. Google Drive API v3 with google-api-python-client handles folders way better and won’t break on you. If you’re just starting out, switch now before you’ve got tons of code to migrate later.