Once you become familiar with the code to call one method on one Google service, you will be able to infer how to call any method on any Google service.
First, we make a connection to the service using the credential
object instantiated in the previous example:
service = build(
SERVICE_NAME,
SERVICE_VERSION,
credentials=credentials)
Then, we can call methods provided by the service. What methods are available?
https://cloud.google.com/resource-manager/docs/apis
What is the underlying REST request for Projects.Create?
https://cloud.google.com/resource-manager/reference/rest/v1/projects/create
OK... Let's write the code.
The create
method expects a body minimally containing the Project ID. Project IDs are unique identifiers. I recommend that you use a system for naming your projects to help you identify them. The method also accepts a Project Name, Labels, details of the Project's parents etc.
operation1 = service.projects().create(
body={
"project_id": PROJECT_ID
}
).execute()
Project creation is handled asynchronously. We are given an Operation object that we must poll to determine when the Project is created. Operations have a Name property that uniquely identifies the operation. The next section of code polls the platform "Are we done yet?". The project will be created when our new operation includes a Done
property that is True
.
name = operation1["name"]
while True:
operation2 = service.operations().get(
name=name
).execute()
if "done" in operation2:
if (operation2["done"]):
break
time.sleep(1)
For completeness, and hopefully many years from now after much happy use of your project, you may need to delete your project. We simply call the delete method and provide our Project ID. This also returns an operation but I'll leave it to you to poll the operation until it completes
operation3 = service.projects().delete(
projectId=PROJECT_ID
).execute()
That's it!