Create a space

This guide explains how to use the create() method on the Space resource of the Google Chat API to create a named space.

The Space resource represents a place where people and Chat apps can send messages, share files, and collaborate. There are several types of spaces:

  • Direct messages (DMs) are conversations between two users or a user and a Chat app.
  • Group chats are conversations between three or more users and Chat apps.
  • Named spaces are persistent places where people send messages, share files, and collaborate.

A named space is a place where people send messages, share files, and collaborate. Named spaces can include Chat apps. Named spaces include extra features that unnamed group conversations and direct messages don't have, such as space managers who can apply administrative settings, descriptions, and add or remove people and apps. After creating a named space, the only member of the space is the authenticated user. The space doesn't include other people or apps; not even the Chat app that creates it. To add members to a space, see Create a membership.

To create a named space with multiple members—an unnamed group chat between three or more people, or a direct message conversation between two people, or a person and the Chat app calling the Chat API—set up a space instead.

Prerequisites

Node.js

Python

Java

Apps Script

Create a named space as a user

To create a named space with user authentication, pass the following in your request:

  • Specify the chat.spaces.create or chat.spaces authorization scope.
  • Call the CreateSpace() method, passing space as an instance of Space with the following fields:
    • spaceType set to SPACE.
    • displayName set to the user-visible name of the space.
    • Optionally, set other attributes, like the following:
      • spaceDetails- a user-visible description and set of guidelines for the space.
      • predefinedPermissionSettings- predefined permissions for the space. For example, you can configure it so that all members or only space managers can post messages.

Here's how to create a named space:

Node.js

chat/client-libraries/cloud/create-space-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.create'];

// This sample shows how to create a named space with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    space: {
      spaceType: 'SPACE',
      // Replace DISPLAY_NAME here.
      displayName: 'DISPLAY_NAME'
    }
  };

  // Make the request
  const response = await chatClient.createSpace(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_space_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.spaces.create"]

def create_space_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateSpaceRequest(
        space = {
            "space_type": 'SPACE',
            # Replace DISPLAY_NAME here.
            "display_name": 'DISPLAY_NAME'
        }
    )

    # Make the request
    response = client.create_space(request)

    # Handle the response
    print(response)

create_space_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateSpaceUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateSpaceRequest;
import com.google.chat.v1.Space;

// This sample shows how to create space with user credential.
public class CreateSpaceUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.spaces.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateSpaceRequest.Builder request = CreateSpaceRequest.newBuilder()
        .setSpace(Space.newBuilder()
          .setSpaceType(Space.SpaceType.SPACE)
          // Replace DISPLAY_NAME here.
          .setDisplayName("DISPLAY_NAME"));
      Space response = chatServiceClient.createSpace(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create space with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces.create'
 * referenced in the manifest file (appsscript.json).
 */
function createSpaceUserCred() {
  // Initialize request argument(s)
  const space = {
    spaceType: 'SPACE',
    // TODO(developer): Replace DISPLAY_NAME here
    displayName: 'DISPLAY_NAME'
  };

  // Make the request
  const response = Chat.Spaces.create(space);

  // Handle the response
  console.log(response);
}

Create a named space as a Chat app

App authentication requires one-time administrator approval.

To invite or add a user to a space with app authentication, pass the following in your request:

  • Specify the chat.app.spaces.create or chat.app.spaces authorization scope.
  • Call the create method on the Space resource.
  • Set spaceType to SPACE.
  • Set displayName to the user-visible name of the space. In the following example, displayName is set to API-made.
  • Specify the customer ID of the Google Workspace domain using the customer field.
  • Optionally, set other space attributes, like spaceDetails (a user-visible description and set of guidelines for the space).

Create an API key

To call a Developer Preview API method, you must use a non-public developer preview version of the API discovery document. To authenticate the request, you must pass an API key.

To create the API Key, open your app's Google Cloud project and do the following:

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create credentials > API key.
  3. Your new API key is displayed.
    • Click Copy to copy your API key for use in your app's code. The API key can also be found in the "API keys" section of your project's credentials.
    • Click Restrict key to update advanced settings and limit use of your API key. For more details, see Applying API key restrictions.

Write a script that calls Chat API

Here's how to create a named space:

Python

  1. In your working directory, create a file named chat_space_create_named_app.py.
  2. Include the following code in chat_space_create_named_app.py:

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.app.spaces.create"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then creates a Chat space.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().create(
    
          # Details about the space to create.
          body = {
    
            # To create a named space, set spaceType to SPACE.
            'spaceType': 'SPACE',
    
            # The user-visible name of the space.
            'displayName': 'API-made',
    
            # The customer ID of the Workspace domain.
            'customer': 'CUSTOMER'
          }
    
          ).execute()
    
        # Prints details about the created space.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. In the code, replace the following:

    • API_KEY: the API key you created to build the service endpoint for Chat API.

    • CUSTOMER: the customer ID of the domain of the space in the format customer/{customer} where {customer} is the ID from the Admin SDK customer resource. To create a space in the same Google Workspace organization as the Chat app, use customers/my_customer.

  4. In your working directory, build and run the sample:

    python3 chat_space_create_named_app.py

Open the space in Google Chat

To navigate to the space, use the space's resource ID to build the space's URL. You can find the resource ID from the space name in the Google Chat response body. For example, if your space's name is spaces/1234567, you can navigate to the space using the following URL: https://mail.google.com/chat/u/0/#chat/space/1234567.