We will use Google API Client Libraries for Python for this sample.
There are other libraries. Please see Google Client Libraries Explained for details.
We will use the Cloud Resource Manager API for Creating and Managing Projects.
Let's get started.
Putting it all together...
If you followed the examples above, you should in a directory called my_project_folder
and it hopefully contains a subdirectory called venv
.
Ensure your virtualenv is activated.
All the code can be placed in one file, let's call it create_project.py
.
Create the file create_project.py
in my_project_folder
.
import json
import time
from apiclient.discovery import build
from oauth2client.client import GoogleCredentials
SERVICE_NAME = "cloudresourcemanager"
SERVICE_VERSION = "v1"
# Don't forget to replace YOUR-PROJECT-ID with your choice of Project ID
# Even though the code deletes the Project, change this value each time
PROJECT_ID = "YOUR-PROJECT-ID"
credentials = GoogleCredentials.get_application_default()
service = build(
SERVICE_NAME,
SERVICE_VERSION,
credentials=credentials)
operation1 = service.projects().create(
body={
"project_id": PROJECT_ID
}
).execute()
print(json.dumps(
operation1,
sort_keys=True,
indent=3))
name = operation1["name"]
while True:
operation2 = service.operations().get(
name=name
).execute()
print(json.dumps(
operation2,
sort_keys=True,
indent=3))
if "done" in operation2:
if (operation2["done"]):
break
time.sleep(1)
raw_input("Press Enter to delete the Project...")
operation3 = service.projects().delete(
projectId=PROJECT_ID
).execute()
Save the file and, from the command-prompt type:
python create_project.py
The output should be similar to:
{
"metadata": {
"@type": "type.googleapis.com/google.cloudresourcemanager.v1.ProjectCreationStatus",
"createTime": "2017-12-31T00:00:00.000Z"
},
"name": "operations/pc.1234567890123456789"
}
...
{
"done": true,
"metadata": {
"@type": "type.googleapis.com/google.cloudresourcemanager.v1.ProjectCreationStatus",
"createTime": "2017-12-31T00:00:00.000Z"
"gettable": true,
"ready": true
},
"name": "operations/pc.1234567890123456789",
"response": {
"@type": "type.googleapis.com/google.cloudresourcemanager.v1.Project",
"createTime": "2017-12-31T00:00:00.000Z",
"lifecycleState": "ACTIVE",
"projectId": "your-project-id",
"projectNumber": "123456789012"
}
}
...
Press Enter to delete the Project...