Search for spaces
Stay organized with collections
Save and categorize content based on your preferences.
This guide explains how to use the
search() method on the
Space resource of the
Google Chat API to search for named spaces in a Google Workspace organization.
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.
If you are a Google Workspace administrator and want to search across all spaces in your organization, including private spaces you haven't joined, see Search for and manage spaces as a Google Workspace administrator to call the API with administrator privileges (useAdminAccess=true).
When searching for spaces with user authentication without administrator privileges, the method searches named spaces (spaceType of SPACE) that the authenticated user has access to, such as spaces they are a member of, within their organization.
Prerequisites
Node.js
- A Business or Enterprise Google Workspace account with access to Google Chat.
- Set up your environment:
- Create a Google Cloud project.
- Configure the OAuth consent screen.
- Enable and configure the Google Chat API with a name, icon, and description for your Chat app.
- Install the Node.js Cloud Client Library.
-
Create OAuth client ID credentials for a desktop application. To run the sample in this
guide, save the credentials as a JSON file named
credentials.jsonto your local directory.
- Choose an authorization scope that supports user authentication.
Python
- A Business or Enterprise Google Workspace account with access to Google Chat.
- Set up your environment:
- Create a Google Cloud project.
- Configure the OAuth consent screen.
- Enable and configure the Google Chat API with a name, icon, and description for your Chat app.
- Install the Python Cloud Client Library.
-
Create OAuth client ID credentials for a desktop application. To run the sample in this
guide, save the credentials as a JSON file named
credentials.jsonto your local directory.
- Choose an authorization scope that supports user authentication.
Java
- A Business or Enterprise Google Workspace account with access to Google Chat.
- Set up your environment:
- Create a Google Cloud project.
- Configure the OAuth consent screen.
- Enable and configure the Google Chat API with a name, icon, and description for your Chat app.
- Install the Java Cloud Client Library.
-
Create OAuth client ID credentials for a desktop application. To run the sample in this
guide, save the credentials as a JSON file named
credentials.jsonto your local directory.
- Choose an authorization scope that supports user authentication.
Apps Script
- A Business or Enterprise Google Workspace account with access to Google Chat.
- Set up your environment:
- Create a Google Cloud project.
- Configure the OAuth consent screen.
- Enable and configure the Google Chat API with a name, icon, and description for your Chat app.
- Create a standalone Apps Script project, and turn on the Advanced Chat Service.
- Choose an authorization scope that supports user authentication.
Search for spaces with user authentication
To search for spaces in Google Chat without administrator privileges, pass the following in your request:
- With user authentication, specify the
chat.spaces.readonlyorchat.spacesauthorization scope. - Call the
search()method on theSpaceresource. - Set
useAdminAccesstofalse(or omit the parameter). - Specify the search
queryparameters to filter the results:spaceType = "SPACE"- required whenqueryis specified and the only supported value isSPACE.displayName- filter by space display name using theHAS(:) operator. For example,displayName:"Project". The text to match is tokenized and each token is prefix-matched case-insensitively and independently as a substring anywhere in the space'sdisplayName. Note: WhenuseAdminAccessisfalse,displayNameis required in your query to retrieve meaningful results; otherwise, the method returns an empty response.externalUserAllowed- optionally filter by whether external guests are allowed in the space (trueorfalse).
- Optionally, specify
pageSizeto limit the maximum number of spaces to return (up to1000), orpageTokento retrieve subsequent pages of results. - Optionally, specify
orderByto sort the search results (createTime descorrelevance desc). Note:relevance descis available through the Google Workspace Developer Preview Program.
Across different fields in the query, only AND operators are supported. For example: spaceType = "SPACE" AND displayName:"Hello" AND externalUserAllowed = "true". Within displayName and externalUserAllowed, OR operators are supported if you want to match multiple criteria.
The following example searches for named spaces that contain "Project" in their display name:
Node.js
/**
* This sample shows how to search for spaces without administrator privileges.
*
* It relies on the @google-apps/chat npm package.
*/
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
const{ChatServiceClient}=require('@google-apps/chat');
const{auth}=require('google-auth-library');
asyncfunctionmain(){
// Create a client
constchatClient=newChatServiceClient({
authClient:awaitauth.getClient({
scopes:['https://www.googleapis.com/auth/chat.spaces.readonly']
})
});
// Initialize request arguments.
// When useAdminAccess is false, spaceType and displayName are required in query.
constrequest={
query:'spaceType = "SPACE" AND displayName:"Project"',
useAdminAccess:false
};
// Call the API and iterate over the paginated response
constiterable=chatClient.searchSpacesAsync(request);
forawait(constresultofiterable){
console.log('Found space:',result.space.displayName,result.space.name);
}
}
main().catch(console.error);
Python
"""
This sample shows how to search for spaces without administrator privileges.
"""
fromgoogle.appsimport chat_v1
importgoogle.auth
# Read the documentation for more details:
# https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
defsearch_spaces():
# Create a client
scopes = ["https://www.googleapis.com/auth/chat.spaces.readonly"]
credentials, _ = google.auth.default(scopes=scopes)
client = chat_v1.ChatServiceClient(credentials=credentials)
# Initialize request arguments.
# When use_admin_access is False, space_type and display_name are required in query.
request = chat_v1.SearchSpacesRequest(
query='spaceType = "SPACE" AND displayName:"Project"',
use_admin_access=False
)
# Make the request and iterate over the paginated results.
page_result = client.search_spaces(request)
for result in page_result.results:
print(f"Found space: {result.space.display_name} ({result.space.name})")
if __name__ == "__main__":
search_spaces()
Java
/**
* This sample shows how to search for spaces without administrator privileges.
*/
importcom.google.chat.v1.ChatServiceClient;
importcom.google.chat.v1.ChatServiceClient.SearchSpacesPagedResponse;
importcom.google.chat.v1.SearchSpacesRequest;
importcom.google.chat.v1.SearchSpaceResult;
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
publicclass SearchSpaces{
publicstaticvoidmain(String[]args)throwsException{
// See https://github.com/googleworkspace/java-samples/blob/main/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java
// for an example of how to authenticate the request.
try(ChatServiceClientchatServiceClient=AuthenticationUtils.createClientWithUserCredentials(
ImmutableList.of("https://www.googleapis.com/auth/chat.spaces.readonly"))){
SearchSpacesRequestrequest=SearchSpacesRequest.newBuilder()
.setQuery("spaceType = \"SPACE\" AND displayName:\"Project\"")
.setUseAdminAccess(false)
.build();
SearchSpacesPagedResponseresponse=chatServiceClient.searchSpaces(request);
for(SearchSpaceResultresult:response.iterateAll()){
System.out.printf("Found space: %s (%s)\n",result.space.getDisplayName(),result.space.getName());
}
}
}
}
Apps Script
/**
* This sample shows how to search for spaces without administrator privileges.
*/
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
functionsearchSpaces(){
try{
// Call the API
// When useAdminAccess is false, spaceType and displayName are required in query.
constresponse=Chat.Spaces.search({
query:'spaceType = "SPACE" AND displayName:"Project"',
useAdminAccess:false
});
if(response.results && response.results.length > 0){
response.results.forEach(result=>{
console.log('Found space: %s (%s)',result.space.displayName,result.space.name);
});
}else{
console.log('No matching spaces found.');
}
}catch(err){
console.log('Failed to search spaces: '+err.message);
}
}
The Chat API returns a paginated list of spaces that match the query and are accessible to the calling user.
Related topics
- Create a space
- Set up a space
- Get details about a space
- List spaces
- Update a space
- Delete a space
- Search for and manage spaces as a Google Workspace administrator