Credentials for programmatic access (API key and bearer token)

To work with foundation models in IBM watsonx.ai programmatically, you must authenticate to prove that you are authorized to access watsonx.ai resources.

Get the hostname for the Cloud Pak for Data cluster. You'll specify this hostname whenever the {cluster_url} is requested.

oc get route cpd -n ${PROJECT_CPD_INST_OPERANDS} -ojsonpath='{.spec.host}'
Tip: Another way to find the hostname is to open the Prompt Lab, and then click the View code icon Viiew code icon to see the cURL command that is generated for the request. The segment of the request before /ml` is the cluster hostname.

REST API credentials

For most API methods, you must include a bearer token with your request. You use an API key to generate a bearer token.

To authenticate REST API requests, complete the following steps:

  1. Create a platform API key from the web client. For more information, see Generating API keys.

  2. Use the platform API key to create a bearer token.

    For more information, see Generating an API authorization token.

  3. Specify the bearer token when you submit a REST request.

    curl -X 'POST' https://{cluster_url}/ml/v1/text/generation 
    --header "Authorization: Bearer {token}..."
    

You are responsible for refreshing the token when it expires. To refresh the token, repeat the procedure starting from Step 2.

Python library credentials

You can authenticate API requests submitted from a notebook by using different methods. For more information about the supported methods, see Authentication.

To create credentials by using an API key, complete the following steps:

  1. Create a platform API key from the web client. For more information, see Generating API keys.

  2. Construct a credentials object that has the following information:

    • API key
    • Hostname for your service instance
    • Your user name
    • Software version

The following sample code snippet shows how an API key is used for authentication when using the Python library.

from ibm_watsonx_ai import APIClient
from ibm_watsonx_ai import Credentials

credentials = Credentials(
  url = "{cluster_url}",
  username = "{username}",
  api_key = "{api-key}",
  instance_id = "openshift",
  version = "5.0"
)

client = APIClient(credentials)

For more information, see Authentication.

Learn more

Parent topic: Coding generative AI solutions