Generating an API key and bearer token for authentication

To work with data and assets in your project programmatically, you must authenticate to prove that you are authorized to access watsonx resources.

Procedure

For most API methods, you must include an Identity and Access Management (IAM) bearer token as your access token with the API request. Use your cloud account API key to generate an IAM bearer token.

To generate API credentials, complete the following steps:

  1. Create an API key:

    In your watsonx account on IBM Cloud, from the navigation menu, select Administration > Access (IAM) > (redirect to IBM Cloud IAM) > API keys, and then click Create +. For more information, see IBM Cloud API key.

    Important: For security reasons, the API key is only available to be copied or downloaded at the time of creation. Save the API key for your records.

    In your AWS account, from the navigation menu, select Administration > Access (IAM) > Personal Access Keys, and then click Create +.

  2. Use the API key to create an IAM bearer token.

    For IBM Cloud, run the following command:

    curl -X POST \
    --url https://iam.cloud.ibm.com/identity/token \
    --header "Content-Type: application/x-www-form-urlencoded" \
    --data "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=${APIKEY}"
    

    For AWS, run the following command:

    curl --request POST \
    --url https://<region>.aws.data.ibm.com/api/rest/mcsp/apikeys/token \
    --header 'Content-Type: application/json' \
    --data '{
       "apikey": "${APIKEY}"
    }'
    

    For an AWS account in the GovCloud data center, run the following command:

    curl --request POST \
    --url https:///dai.ibmforusgov.com/api/rest/mcsp/apikeys/token \
    --header 'Content-Type: application/json' \
    --data '{
       "apikey": "${APIKEY}"
    }'
    

    Retrieve the IAM bearer token from the access_token field in the response. You can use the bearer token to authenticate with the watsonx API.

    Important: You are responsible for refreshing the bearer token when it expires by recreating the token.

What to do next

You can invoke the API endpoints by specifying the generated IAM bearer token in the authorization header when you submit a REST API request as follows:

curl -X POST "https://<region>.<cloud-provider-domain>/<api-endpoint>" --header "Authorization: Bearer ${TOKEN} ..."

Set the <cloud-provider-domain> based on the API endpoint you invoke and the <region> to the URL of an available geographical location of your account.

For details about the cloud provider domains and geographical locations for watsonx APIs refer to the API documentation. See Available APIs and SDKs.