如何用Python通过API调用生成Analytics Engine的IAM访问令牌?
I get it—sometimes you need to skip the CLI and make direct API calls to get an IAM access token for Analytics Engine (or any IBM Cloud service). Here's how to replicate the CLI workflow programmatically, plus a simpler shortcut for automation:
Replicating the CLI Login Flow with API Calls
The bx login and bx iam oauth-tokens commands under the hood use IBM Cloud's UAA and IAM Identity APIs. Here's the step-by-step breakdown:
1. Authenticate with your username/password
First, hit the UAA login endpoint to get a UAA access token (this is what bx login does when you enter your credentials):
POST https://api.ng.bluemix.net/UAALoginServerWAR/oauth/token Headers: Content-Type: application/x-www-form-urlencoded Authorization: Basic Y2Y6 # Base64-encoded "cf:" (UAA's default client ID) Form Data: grant_type: password username: your_ibm_cloud_email@example.com password: your_ibm_cloud_password response_type: token
You'll get a JSON response with an access_token (this is the UAA token) and refresh_token.
2. Exchange UAA token for IAM access token
Next, convert that UAA token into an IAM token using the IAM Identity service:
POST https://iam.cloud.ibm.com/identity/token Headers: Content-Type: application/x-www-form-urlencoded Form Data: grant_type: urn:ibm:params:oauth:grant-type:uaa_token uaa_token: [UAA_ACCESS_TOKEN_FROM_STEP_1]
The access_token in this response is the IAM token you need—this is what bx iam oauth-tokens outputs.
Simpler Method: Use an API Key (Skip Username/Password)
If you can create an IBM Cloud API key (go to your IBM Cloud Console > Manage > Access (IAM) > API Keys), this is way easier for automation:
POST https://iam.cloud.ibm.com/identity/token Headers: Content-Type: application/x-www-form-urlencoded Form Data: grant_type: urn:ibm:params:oauth:grant-type:apikey apikey: [YOUR_IBM_CLOUD_API_KEY]
This returns the IAM access token directly—no extra steps needed.
Handling Multiple Accounts/Orgs/Spaces
If you have multiple accounts, after getting your IAM token, you can list your accounts with this API call:
GET https://resource-controller.cloud.ibm.com/v2/accounts Headers: Authorization: Bearer [YOUR_IAM_ACCESS_TOKEN]
Once you pick an account, you can set the context for your API calls by including the account ID in subsequent requests (or use the Resource Controller API to manage org/space assignments).
Verify Your Token (Optional)
To check if your token is valid or see its details (like expiration), use the introspection endpoint:
POST https://iam.cloud.ibm.com/identity/introspect Headers: Content-Type: application/x-www-form-urlencoded Form Data: token: [YOUR_IAM_ACCESS_TOKEN] client_id: test
内容的提问来源于stack exchange,提问作者Chris Snow

