'How to programmatically obtain a google cloud project number using its project id in Python
A google cloud project has both a project id and a project number. How can the project id be used to obtain the project number.
Solution 1:[1]
A version of LlamaD's answer but with a query to speed up the search:
def get_project_number(project_id) -> Optional[str]:
"""Given a project id, return the project number"""
# Create a client
client = resourcemanager_v3.ProjectsClient()
# Initialize request argument(s)
request = resourcemanager_v3.SearchProjectsRequest(query=f"id:{project_id}")
# Make the request
page_result = client.search_projects(request=request)
# Handle the response
for response in page_result:
if response.project_id == project_id:
project = response.name
return project.replace('projects/', '')
Solution 2:[2]
An adaptation of sample code used in the resource manager found here
def get_project_number(project_id):
"""Given a project id, return the project number"""
# Create a client
client = resourcemanager_v3.ProjectsClient()
# Initialize request argument(s)
request = resourcemanager_v3.SearchProjectsRequest()
# Make the request
page_result = client.search_projects(request=request)
# Handle the response
for response in page_result:
if response.project_id == project_id:
project = response.name
return project.replace('projects/', '')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ivanmkc |
Solution 2 | LlamaD |