Authenticate and authorize as a service account

This guide explains how to set up and use a service account to access the Google Chat REST API. First, it walks you through how to create a service account. Then, it demonstrates how to write a script that uses the service account to authenticate with the Chat API and post a message in a Chat space.

Service accounts let Chat apps send asynchronous messages to Google Chat, which lets them:

  • Notify users when a long-running background job finishes running.
  • Alert users that a server has gone offline.
  • Ask a customer support person to tend to a newly opened customer case.

When authenticated with a service account, to get data about or perform actions in a Chat space, Chat apps must have membership in the space. For example, to list members of a space, or to create a message in a space, the Chat app has to itself be a member of the space.

If your Chat app needs to access user data or perform actions on a user's behalf, authenticate with user credentials instead.

To learn more about when Chat apps require authentication and what kind of authentication to use, see Types of required authentication in the Chat API authentication and authorization overview.

Prerequisites

To run the example in this guide, you need the following prerequisites:

Python

Step 1: Install the Google client library

If you haven't already installed the Google client libraries for your language of choice, run the following command in your command line interface:

Python

pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client

You can use any language supported by our client libraries.

Step 2: Create a service account in Google Cloud Console

Create a service account that your Chat app will use to access Google APIs.

Create a service account:

To create a service account, follow these steps:

  1. Open the Google Cloud console.
  2. At the top-left, click Menu > IAM & Admin > Service Accounts.
  3. Click Create service account.
  4. Fill in the service account details, then click Create and continue.
  5. Optional: Assign roles to your service account to grant access to your Google Cloud project's resources. For more details, refer to Granting, changing, and revoking access to resources.
  6. Click Continue.
  7. Optional: Enter users or groups that can manage and perform actions with this service account. For more details, refer to Managing service account impersonation.
  8. Click Done.

The service account appears on the service account page. Next, create a private key for the service account.

Create a private key

To create a private key for the service account, follow these steps:

  1. Open the Google Cloud console.
  2. At the top-left, click Menu > IAM & Admin > Service Accounts.
  3. Select your service account.
  4. Click Keys > Add keys > Create new key.
  5. Select JSON, then click Create.

    Your new public/private key pair is generated and downloaded to your machine as a new file. This file is the only copy of this key. For information about how to store your key securely, see Managing service account keys.

  6. Click Close.

For more information about service accounts, see service accounts in the Google Cloud IAM documentation.

Step 3: Apply credentials to HTTP request headers

Next, apply necessary credential headers to all requests made by an httplib2.Http instance. The following code snippet shows how to create a credential object, using a private key like the one created in step 2:

Python

from oauth2client.service_account import ServiceAccountCredentials

SCOPES = ['https://www.googleapis.com/auth/chat.bot']
CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
    'service_account.json', SCOPES)

Step 4: Build a service endpoint and call the Chat API

Use a client library to call the Google Chat REST API.

The following code snippet creates a service endpoint to the Chat REST API by creating an HTTP client and authorizing with service account credentials:

Python

from apiclient.discovery import build
chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))

Next, create a new message with space.name as the parent and JSON payload in the message body, and call the execute() method:

Python

result = chat.spaces().messages().create(

    # Replace {space} with a space name.
    # Obtain the space name from the spaces resource of Chat API,
    # or from a space's URL.
    parent='spaces/{space}',
    body={'text': 'Test message'}).execute()

print(result)

Run the complete example

The following code authenticates with the Chat REST API using a service account, then posts a message to a Chat space:

Python

from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/chat.bot']
CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
    'service_account.json', SCOPES)

chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
result = chat.spaces().messages().create(
    parent='spaces/{space}',# replace {space} with a space name
    body={'text': 'Test message'}).execute()

print(result)

To run the sample, save the code in a file named chat_create_message.py, then execute the following command from the command line:

Python

python chat_create_message.py

Your script makes an authenticated request to the Chat REST API, which responds by posting a message in a Chat space as a Chat app.

Troubleshoot the example

This section describes common issues that you might encounter while attempting to run this sample.

You are not permitted to use this app

When running chat_create_message.py, you might receive an error that says:

<HttpError 403 when requesting https://chat.googleapis.com/v1/spaces/{space}/messages?alt=json returned "You are not permitted to use this app". Details: "You are not permitted to use this app">

This error message means that the Chat app associated with the service account you created doesn't have permission to post Chat messages in the Chat space you are trying to post to.

To resolve the error, add the Chat app associated with the service account to the Chat space specified in chat_create_message.py.

Next step

Learn what else Chat API can do by reviewing the Chat API reference documentation.