Package: watson-developer-cloud
Python client library to quickly get started with the variousWatson
APIsservices.Table of ContentsBefore you beginInstallationExamplesRunning in IBM CloudAuthenticationGetting credentialsIAMUsername and passwordPython versionChanges for v1.0Changes for v2.0MigrationConfiguring the http
clientDisable SSL certificate
verificationSending request headersParsing HTTP response infoDependenciesLicenseContributingBefore you beginYou need anIBM
Cloudaccount.InstallationNote: We are moving toibm-watson. All versions prior to v3.0.0 can
still be found inwatson-developer-cloudTo install, usepiporeasy_install:pipinstall--upgradewatson-developer-cloudoreasy_install--upgradewatson-developer-cloudNote the following:If you run into permission issues try:sudo-Hpipinstall--ignore-installedsixwatson-developer-cloudFor more details see#225In case you run into problems installing the SDK in DSX, try!pip install --upgrade pipRestarting the kernelFor more details see#405ExamplesTheexamplesfolder has basic and advanced examples. The examples within each service
assume that you already haveservice
credentials.Running in IBM CloudIf you run your app in IBM Cloud, the SDK gets credentials from the`VCAP_SERVICES<https://console.bluemix.net/docs/services/watson/getting-started-variables.html>`__
environment variable.AuthenticationWatson services are migrating to token-based Identity and Access
Management (IAM) authentication.With some service instances, you authenticate to the API by using`IAM <#iam>`__.In other instances, you authenticate by providing the`username and
password <#username-and-password>`__for the service instance.Note:Authenticating with the X-Watson-Authorization-Token header is
deprecated. The token continues to work with Cloud Foundry services, but
is not supported for services that use Identity and Access Management
(IAM) authentication. Seeherefor details.Getting credentialsTo find out which authentication to use, view the service credentials.
You find the service credentials for authentication the same way for all
Watson services:Go to the IBM CloudDashboardpage.Either click an existing Watson service instance in yourresource
listor click**Create resource
> AI**and create a
service instance.Click on theManageitem in the left nav bar of your service
instance.On this page, you should be able to see your credentials for accessing
your service instance.Supplying credentialsThere are two ways to supply the credentials you found above to the SDK
for authentication.Credential file (easier!)With a credential file, you just need to put the file in the right place
and the SDK will do the work of parsing and authenticating. You can get
this file by clicking theDownloadbutton for the credentials in theManagetab of your service instance.The file downloaded will be calledibm-credentials.env. This is the
name the SDK will search for andmustbe preserved unless you want
to configure the file path (more on that later). The SDK will look for
youribm-credentials.envfile in the following places (in order):Your system’s home directoryThe top-level directory of the project you’re using the SDK inAs long as you set that up correctly, you don’t have to worry about
setting any authentication options in your code. So, for example, if you
created and downloaded the credential file for your Discovery instance,
you just need to do the following:discovery=DiscoveryV1(version='2018-08-01')And that’s it!If you’re using more than one service at a time in your code and get two
differentibm-credentials.envfiles, just put the contents together
in oneibm-credentials.envfile and the SDK will handle assigning
credentials to their appropriate services.If you would like to configure the location/name of your credential
file, you can set an environment variable calledIBM_CREDENTIALS_FILE.This will take precedence over the locations
specified above.Here’s how you can do that:exportIBM_CREDENTIALS_FILE="<path>"where<path>is something like/home/user/Downloads/<file_name>.env.ManuallyIf you’d prefer to set authentication values manually in your code, the
SDK supports that as well. The way you’ll do this depends on what type
of credentials your service instance gives you.IAMIBM Cloud is migrating to token-based Identity and Access Management
(IAM) authentication. IAM authentication uses a service API key to get
an access token that is passed with the call. Access tokens are valid
for approximately one hour and must be regenerated.You supply either an IAM serviceAPI keyor anaccess token:Use the API key to have the SDK manage the lifecycle of the access
token. The SDK requests an access token, ensures that the access
token is valid, and refreshes it if necessary.Use the access token if you want to manage the lifecycle yourself.
For details, seeAuthenticating with IAM
tokens.Supplying the IAM API key# In the constructor, letting the SDK manage the IAM tokendiscovery=DiscoveryV1(version='2018-08-01',url='<url_as_per_region>',iam_apikey='<iam_apikey>',iam_url='<iam_url>')# optional - the default value is https://iam.bluemix.net/identity/token# after instantiation, letting the SDK manage the IAM tokendiscovery=DiscoveryV1(version='2018-08-01',url='<url_as_per_region>')discovery.set_iam_apikey('<iam_apikey>')Supplying the access token# in the constructor, assuming control of managing IAM tokendiscovery=DiscoveryV1(version='2018-08-01',url='<url_as_per_region>',iam_access_token='<iam_access_token>')# after instantiation, assuming control of managing IAM tokendiscovery=DiscoveryV1(version='2018-08-01',url='<url_as_per_region>')discovery.set_iam_access_token('<access_token>')Username and passwordfromwatson_developer_cloudimportDiscoveryV1# In the constructordiscovery=DiscoveryV1(version='2018-08-01',url='<url_as_per_region>',username='<username>',password='<password>')# After instantiationdiscovery=DiscoveryV1(version='2018-08-01',url='<url_as_per_region>')discovery.set_username_and_password('<username>','<password>')Python versionTested on Python 2.7, 3.4, 3.5, and 3.6.Changes for v1.0Version 1.0 focuses on the move to programmatically-generated code for
many of the services. See thechangelogfor the details.Changes for v2.0DetailedResponsewhich contains the result, headers and HTTP status
code is now the default response for all methods.fromwatson_developer_cloudimportAssistantV1assistant=AssistantV1(username='xxx',password='yyy',url='<url_as_per_region>',version='2018-07-10')response=assistant.list_workspaces(headers={'Custom-Header':'custom_value'})print(response.get_result())print(response.get_headers())print(response.get_status_code())See thechangelogfor the details.MigrationThis version includes many breaking changes as a result of standardizing
behavior across the new generated services. Full details on migration
from previous versions can be foundhere.Configuring the http client (Supported from v1.1.0)To set client configs like timeout use thewith_http_config()function and pass it a dictionary of configs.fromwatson_developer_cloudimportAssistantV1assistant=AssistantV1(username='xxx',password='yyy',url='<url_as_per_region>',version='2018-07-10')assistant.set_http_config({'timeout':100})response=assistant.message(workspace_id=workspace_id,input={'text':'What\'s the weather like?'}).get_result()print(json.dumps(response,indent=2))Disable SSL certificate verificationFor ICP(IBM Cloud Private), you can disable the SSL certificate
verification by:service.disable_SSL_verification()Sending request headersCustom headers can be passed in any request in the form of adictas:headers={'Custom-Header':'custom_value'}For example, to send a header calledCustom-Headerto a call in
Watson Assistant, pass the headers parameter as:fromwatson_developer_cloudimportAssistantV1assistant=AssistantV1(username='xxx',password='yyy',url='<url_as_per_region>',version='2018-07-10')response=assistant.list_workspaces(headers={'Custom-Header':'custom_value'}).get_result()Parsing HTTP response infoIf you would like access to some HTTP response information along with
the response model, you can set theset_detailed_response()toTrue. Since Python SDKv2.0, it is set toTruefromwatson_developer_cloudimportAssistantV1assistant=AssistantV1(username='xxx',password='yyy',url='<url_as_per_region>',version='2018-07-10')assistant.set_detailed_response(True)response=assistant.list_workspaces(headers={'Custom-Header':'custom_value'}).get_result()print(response)This would give an output ofDetailedResponsehaving the structure:{'result':<responsereturnedbyservice>,'headers':{<httpresponseheaders>},'status_code':<httpstatuscode>}You can use theget_result(),get_headers()and
get_status_code() to return the result, headers and status code
respectively.Using WebsocketsThe Text to Speech service supports synthesizing text to spoken audio
using web sockets with thesynthesize_using_websocket. The Speech to
Text service supports recognizing speech to text using web sockets with
therecognize_using_websocket. These methods need a custom callback
class to listen to events. Below is an example ofsynthesize_using_websocket. Note: The service accepts one request
per connection.fromwatson_developer_cloud.websocketimportSynthesizeCallbackclassMySynthesizeCallback(SynthesizeCallback):def__init__(self):SynthesizeCallback.__init__(self)defon_audio_stream(self,audio_stream):returnaudio_streamdefon_data(self,data):returndatamy_callback=MySynthesizeCallback()service.synthesize_using_websocket('I like to pet dogs',my_callback,accept='audio/wav',voice='en-US_AllisonVoice')Dependenciesrequestspython_dateutil>= 2.5.3responsesfor testingFollowing for web sockets support in speech to textwebsocket-client0.48.0ContributingSeeCONTRIBUTING.md.LicenseThis library is licensed under theApache 2.0
license.