1

Every time I try and use instance templates in the python Compute Engine API it outputs the URL incorrectly.

Ex: Using PyCharm and Python 3.9

compute = googleapiclient.discovery.build('compute', 'v1')

host_project = 'testproject123'
host_zone = 'us-central1-a'

vm_name = host_project+'-api-fetch'
instance_template = 'projects/testproject123/global/instanceTemplates/testproject123-api-1'

compute.instances().insert(project=host_project, zone=host_zone, sourceInstanceTemplate=instance_template).execute()

Which returns

Error
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "[PATH]main.py", line 14, in <module>
    compute.instances().insert(project=host_project, zone=host_zone, sourceInstanceTemplate=instance_template).execute()
  File "C:\Users\[USER]\AppData\Roaming\Python\Python39\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\[USER]\AppData\Roaming\Python\Python39\site-packages\googleapiclient\http.py", line 935, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://compute.googleapis.com/compute/v1/projects/testproject123/zones/us-central1-a/instances?sourceInstanceTemplate=projects%2Ftestproject123%2Fglobal%2FinstanceTemplates%2Ftestproject123-api-1&alt=json returned "Required field 'resource' not specified". Details: "[{'message': "Required field 'resource' not specified", 'domain': 'global', 'reason': 'required'}]">

Any idea why it keeps converting the '/' to %2? I am assuming that's what is causing the issue but I can't seem to trace it back or find a simple fix.

Slacker101
  • 23
  • 6
  • Note: It is normal to URL encode some characters in API requests. The character `/` is encoded to `%2F` by the client library. – John Hanley Jun 14 '21 at 02:01

1 Answers1

1

Evidently even though body is optional in https://googleapis.github.io/google-api-python-client/docs/dyn/compute_v1.instances.html#insert a body with name is still required. Adding that fixed the issue completely.

%2F was properly working as URL encoded slash the whole time.

Slacker101
  • 23
  • 6