使用Python桌面应用调用Google Cloud APIs与Oauth2获取项目IAM策略时遭遇400无效参数错误求助
Looking at your error message, the key clue is the request path: https://cloudresourcemanager.googleapis.com/v1/projects/projects%2Fproject-name:testIamPermissions. Notice the duplicated projects/ prefix (projects/projects%2Fproject-name) — that's exactly what's causing the 400 invalid argument error.
The Root Cause: Incorrect Resource Parameter Format
The Google Cloud Python client library automatically prepends projects/ to the resource parameter when you call methods under service.projects(). By manually constructing resource = 'projects/' + prj, you're making the final resource path double up on the prefix, which the API rejects as invalid.
Here's the quick fix — just pass the raw project ID as the resource parameter, no extra prefix needed:
for prj in proj: # Use the project ID directly, no "projects/" prefix required # For testIamPermissions, you MUST specify permissions in the body (can't pass None) test_perms_body = {"permissions": ["resourcemanager.projects.getIamPolicy", "resourcemanager.projects.list"]} response1 = service.projects().testIamPermissions(resource=prj, body=test_perms_body).execute() response2 = service.projects().listOrgPolicies(resource=prj).execute() # For getIamPolicy, specifying a policy version is recommended (version 3 is current) get_policy_body = {"options": {"requestedPolicyVersion": 3}} response3 = service.projects().getIamPolicy(resource=prj, body=get_policy_body).execute()
A couple of extra notes on the method calls:
testIamPermissionsrequires you to pass a list of permissions to test in thebodyparameter — passingbody=Nonewill also trigger an invalid argument error, so don't skip this.- For
getIamPolicy, specifyingrequestedPolicyVersion: 3ensures you get the latest IAM policy format, which is Google's recommended practice.
About API Version (v1 vs v3)
The API version isn't the issue here:
- The v1 API is fully supported for project management and IAM operations — this is exactly what you need for your use case.
- The v3 API is focused on folder-related operations, so it doesn't affect your project-level calls at all.
Other Things to Check
- OAuth Scopes: Your
https://www.googleapis.com/auth/cloud-platformscope is more than sufficient for these operations, so that's not the problem. - Valid Project IDs: Double-check that the project IDs in your
projlist are correct (no typos, extra spaces, or invalid characters). - Account Permissions: While this isn't causing your current 400 error, make sure the account you're authenticating with has the necessary permissions on the projects (e.g.,
resourcemanager.projects.getIamPolicyor a broader role likeProject IAM Admin). If permissions are missing, you'll get a 403 error instead of 400.
内容的提问来源于stack exchange,提问作者pras123

