1

I am trying to create a document on Google Docs API using python, but when I use the script I get this error - NameError: name 'service' is not defined.

This is the script I am using (from https://developers.google.com/docs/api/how-tos/documents#python):

title = 'My Document'
body = {
    'title': title
}
doc = service.documents() \
    .create(body=body).execute()
print('Created document with title: {0}'.format(
    doc.get('title')))

Any help to fix this would be much appreciated!

3
  • You should provide a minimal reproducible example so we can see why you're expecting service to be defined at that point. Otherwise I don't see how we can possibly help you. The only possible answer with what you've given us is that you never defined service, but obviously that's what the error is telling you anyway. Commented Jan 5, 2021 at 17:16
  • Hi Random Davis, my confusion stems from Google Docs providing the above as an example of how to create a document, but it doesn't work. Here is the link - developers.google.com/docs/api/how-tos/documents Commented Jan 5, 2021 at 20:02
  • Does my answer help? Commented Jan 5, 2021 at 21:08

1 Answer 1

1

I posted this as a comment but I might as well have it be an answer, since I found the issue.

The issue is that you can't just run that code alone and expect anything to work. From looking around the API documentation you copied that code from (here), it's clear that you didn't start with the Python Quickstart page, which has an example script that sets up the service variable among other things. Once you use that code to define and set up service, the code from your example should work as expected.

Here's an example of what I meant - just took the example, pasted it here, and pasted in the code that you were trying to run below the comment # Create a document called 'My Document':

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/documents.readonly']

# The ID of a sample document.
DOCUMENT_ID = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE'

def main():
    """Shows basic usage of the Docs API.
    Prints the title of a sample document.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('docs', 'v1', credentials=creds)

    # Create a document called 'My Document'
    title = 'My Document'
    body = { 'title': title }
    doc = service.documents().create(body=body).execute()
    print('Created document with title: {0}'.format(doc.get('title')))


if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

5 Comments

So I have now run the code with the Python Quickstart page script, but it still says service is not defined (even though it looks like it is)?
You have to actually run your code in the same scope that service was defined in. In the example, it's defined in main(), so if you're trying to access it outside of main, that's outside of its scope, so it will be undefined still. You could also just pass service to the function that requires it.
I'm not sure I follow, can you provide an example in the Google Docs API context?
@rafholder okay I put in an example, it's below the comment # Create a document called 'My Document'. That's what I meant by putting it in scope. You could also put that code inside a function, and pass service to that function.
Thanks Random Davis!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.