{"id":13801229,"url":"https://github.com/watson-developer-cloud/salesforce-sdk","last_synced_at":"2026-03-02T19:32:18.993Z","repository":{"id":66139965,"uuid":"109404898","full_name":"watson-developer-cloud/salesforce-sdk","owner":"watson-developer-cloud","description":"A Salesforce library for communicating with the IBM Watson REST APIs","archived":false,"fork":false,"pushed_at":"2020-07-20T16:15:45.000Z","size":30861,"stargazers_count":29,"open_issues_count":3,"forks_count":35,"subscribers_count":24,"default_branch":"master","last_synced_at":"2025-01-07T12:30:41.937Z","etag":null,"topics":["salesforce","watson","watson-services"],"latest_commit_sha":null,"homepage":null,"language":"Apex","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/watson-developer-cloud.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/Contributing.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-11-03T14:26:11.000Z","updated_at":"2024-06-17T15:57:21.000Z","dependencies_parsed_at":null,"dependency_job_id":"b7f0ac8c-3606-4ceb-b2e5-db08236b91bd","html_url":"https://github.com/watson-developer-cloud/salesforce-sdk","commit_stats":null,"previous_names":[],"tags_count":51,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fsalesforce-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fsalesforce-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fsalesforce-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/watson-developer-cloud%2Fsalesforce-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/watson-developer-cloud","download_url":"https://codeload.github.com/watson-developer-cloud/salesforce-sdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240578119,"owners_count":19823571,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["salesforce","watson","watson-services"],"created_at":"2024-08-04T00:01:20.742Z","updated_at":"2026-03-02T19:32:18.944Z","avatar_url":"https://github.com/watson-developer-cloud.png","language":"Apex","funding_links":[],"categories":["Data \u0026 AI"],"sub_categories":[],"readme":"# IBM Watson Salesforce SDK\n\n[![Build Status](https://travis-ci.org/watson-developer-cloud/salesforce-sdk.svg?branch=master)](https://travis-ci.org/watson-developer-cloud/salesforce-sdk/)\n[![Slack](http://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n\nThe IBM Watson Salesforce SDK uses the [Watson API](http://www.ibm.com/watson/developercloud/) services to help you solve complex problems using Apex in your Salesforce environment. If you'd like, you can follow along with our video playlist [here](https://www.youtube.com/playlist?list=PLZDyxLlNKRY8qrs90oRPvVHocJhYOOj3n) to start using the SDK. Otherwise, continue reading to learn how to get started.\n\n**NOTE:** This is a Community SDK and not an official SDK. See https://cloud.ibm.com/docs/watson?topic=watson-using-sdks#community-sdks\n\n## Before you begin\n\n* You need an [IBM Cloud][ibm-cloud-onboarding] account.\n\n### Getting credentials\nTo find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:\n\n1. Go to the IBM Cloud [Dashboard](https://cloud.ibm.com) page.\n1. Either click an existing Watson service instance in your [resource list](https://cloud.ibm.com/resources) or click [**Create resource \u003e AI**](https://cloud.ibm.com/catalog?category=ai) and create a service instance.\n1. Click on the **Manage** item in the left nav bar of your service instance.\n\nOn this page, you should be able to see your credentials for accessing your service instance.\n\nYou'll also need a Salesforce account to run your Apex code. To get one, you can visit [this link](https://developer.salesforce.com/signup).\n\n## Installation\n\nThere are three supported installation methods: automatically using Salesforce DX, manually using Salesforce DX, and manually using the Ant build tool. By default, all classes in the SDK will be deployed to your Salesforce org, but using Ant allows you to specify which services you want to deploy to save space. Note though that this is **only** supported with the Ant build tool method.\n\n### Salesforce DX automatic deployment\n\nYou can automatically deploy the SDK to a new scratch environment using the _Deploy to SFDX_ button.\n\n_Note: To use the automatic deployment button, you must log in using a **Dev Hub** org. If you do not have one, there should be a link to get one after you click the button._\n\n[![Deploy](https://deploy-to-sfdx.com/dist/assets/images/DeployToSFDX.svg)](https://deploy-to-sfdx.com/)\n\n### Salesforce DX manual deployment\n\nYou can also manually deploy the SDK code using the Salesforce DX CLI, which you can install [here](https://developer.salesforce.com/tools/sfdxcli).\n\nThe first step to manual deployment is cloning the repository from GitHub using the following command:\n\n```bash\ngit clone https://github.com/watson-developer-cloud/salesforce-sdk\n```\n\nBe sure to navigate to the cloned directory before continuing.\n\nTo deploy to a scratch org, do the following:\n\n1. Create a new scratch environment (optional if you don't want to re-use an existing one):\n\n    ```bash\n    sfdx force:org:create -a watson-sdk -s -f config/project-scratch-def.json\n    ```\n\n1. Push the source to the scratch environment:\n\n    ```bash\n    sfdx force:source:push\n    ```\n\nIf you want to use the Watson SDK within a non-scratch environment you can follow these steps:\n\n1. Authenticate the Salesforce DX CLI to the target environment:\n\n    ```bash\n    sfdx force:auth:web:login --setdefaultusername\n    ```\n    In the browser window that opens, sign in to your org with your credentials. More information [here](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_auth_web_flow.htm)\n\n1. Convert the source code:\n\n    ```bash\n    sfdx force:source:convert -d mdapioutput/\n    ```\n\n1. Deploy the source code:\n\n    ```bash\n    sfdx force:mdapi:deploy -d mdapioutput/ -w 100\n    ```\n\n## Installation using the Ant Build Tool\n\nFinally, you can also install or update the SDK using the Ant Build Tool. This method also allows you to specify which services you'd like to deploy.\n\n1. Clone this repository from GitHub using the following command:\n\n    ```bash\n    git clone https://github.com/watson-developer-cloud/salesforce-sdk\n    ```\n\n1. Edit `install/build.properties` to insert your Salesforce username and password.  Since you will be using the API to access Salesforce, remember to [append your Security Token](http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_concepts_security.htm#topic-title_login_token) to your password.\n\n1. Open your command line to the `install` folder, then deploy using Ant:\n\n    ```bash\n    ant deployWatson\n    ```\n\n    By default, this will deploy all of the classes. To specify a service, use the `-Dservice` flag. Here is an example of just deploying the Watson Assistant service:\n\n    ```bash\n    ant deployWatson -Dservice=assistant\n    ```\n\n    Valid service names are all services listed [here](https://cloud.ibm.com/catalog/?category=watson) written as one word (e.g. Visual Recognition becomes visualrecognition). The parameter is case-insensitive. To deploy multiple services, just run the command again with the next desired service flag.\n\n## Authentication\nTo access your Watson services through Apex, you'll need to authenticate with your service credentials. There are two ways to do this: [using a credential file](#using-a-credential-file) or [specifying credentials in the Apex code](#specifying-credentials-in-the-apex-code).\n\n**Note:** Previously, it was possible to authenticate using a token in a header called `X-Watson-Authorization-Token`. This method 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. See [here](#using-iam) for details.\n\n### Using a credential file\n\nWith a credential file, you just need to put the file in the right place and the SDK will do the work of parsing it and authenticating. You can get this file by clicking the **Download** button for the credentials in the **Manage** tab of your service instance.\n\nOnce you've downloaded your file, you'll need to do the following:\n\n1. Log in to your Salesforce dashboard\n1. Go to _Setup_ by clicking on the gear icon on the top right of the page\n1. Enter _Static Resources_ in the quick find box and select the highlighted entry\n1. Create a new static resource\n1. Enter the name **ibm_credentials** (:point_left: this must be the name!)\n1. Upload the file you downloaded from the service dashboard page\n1. Set the cache control to **Public**\n\nOnce this is done, you're good to go! As an example, if you uploaded a credential file for your Discovery service, you just need to do the following in your code\n\n```java\nIBMWatsonAuthenticator authenticator = new IBMWatsonConfigBasedAuthenticatorFactory('discovery');\nIBMDiscoveryV1 discovery = new IBMDiscoveryV1('2019-04-30', authenticator);\n```\n\nand you'll be authenticated :white_check_mark:\n\nIf you're using more than one service at a time in your code and get two different credetnial files, just put the contents together in one file and upload it to your Static Resources with the same name as above. The SDK will handle assigning credentials to their appropriate services.\n\n### Specifying credentials in the Apex code\n\nIf the methods above don't work for you, setting credentials in the code is always an option. The examples below just show the minimum required arguments for each `IBMWatsonAuthenticator` implementation, but there are other constructors you can play with for more options.\n\n#### Username and password\n\n```java\nIBMWatsonAuthenticator authenticator = new IBMWatsonBasicAuthenticator('USERNAME', 'PASSWORD');\nIBMDiscoveryV1 discovery = new IBMDiscoveryV1('2019-04-30', authenticator);\ndiscovery.setServiceURL('URL');\n```\n\n#### Using IAM\n\n```java\nIBMWatsonAuthenticator authenticator = new IBMWatsonIAMAuthenticator('API_KEY');\nIBMDiscoveryV1 service = new IBMDiscoveryV1('2019-04-30', authenticator);\nservice.setServiceURL('URL');\n```\n\n#### ICP\n\n```java\nIBMWatsonAuthenticator authenticator =\n  new IBMWatsonBasicAuthenticator('USERNAME', 'PASSWORD');\nIBMDiscoveryV1 service = new IBMDiscoveryV1('2019-04-30', authenticator);\nservice.setServiceURL('SERVICE ICP URL');\n```\n\n**Note:** Make sure you've got your self-signed certificate all set up in your Salesforce organization for this to work properly.\n\n#### Cloud Pak for Data\n\n```java\nIBMWatsonAuthenticator authenticator =\n  new IBMWatsonCloudPakForDataAuthenticator('CP4D TOKEN EXCHANGE BASE URL', 'USERNAME', 'PASSWORD');\nIBMDiscoveryV1 service = new IBMDiscoveryV1('2019-04-30', authenticator);\nservice.setServiceURL('SERVICE CP4D URL');\n```\n\n### Setting remote site settings\n\nThe final piece of setup to access Watson services from your Salesforce environment is setting your remote site settings. To do so:\n\n1. Go to _Setup_ by clicking on the gear icon on the top right of the Salesforce dashboard\n1. Enter _Remote Site Settings_ in the quick find box and select the highlighted entry\n1. Click _New Remote Site_\n1. Add whatever name you desire, with the following URL: `https://gateway.watsonplatform.net/`\n1. Click _Save_\n\nIf you're authenticating with IAM, you'll also need to add your IAM URL in your remote site settings. The default URL is `https://iam.cloud.ibm.com/identity/token`.\n\n## Examples\n\nGetting started using a service is very simple! All services follow the same pattern of service instantiation, option building, and requesting. To get an idea, below is an example of using the Discovery service to get a list of your current environments:\n\n```java\nIBMWatsonAuthenticator authenticator = new IBMWatsonIAMAuthenticator('API_KEY');\nIBMDiscoveryV1 discovery = new IBMDiscoveryV1('2019-04-30', authenticator);\n\n// configuring options for listing environments\nIBMDiscoveryV1Models.ListEnvironmentsOptions options =\n  new IBMDiscoveryV1Models.ListEnvironmentsOptionsBuilder()\n    .build();\n\n// making request\nIBMDiscoveryV1Models.ListEnvironmentsResponse environmentList = discovery.listEnvironments(options);\nSystem.debug(environmentList);\n```\n\nSimilarly, here is an example of creating an intent in the Watson Assistant service:\n\n```java\nIBMWatsonAuthenticator authenticator = new IBMWatsonIAMAuthenticator('API_KEY');\nIBMAssistantV1 assistant = new IBMAssistantV1('2019-02-28', authenticator);\n\n// configuring options for creating intent\nIBMAssistantV1Models.CreateIntentOptions options =\n  new IBMAssistantV1Models.CreateIntentOptionsBuilder()\n    .workspaceId('\u003cworkspace_id\u003e')\n    .intentName('MyIntent')\n    .description('This is an example of creating an intent!')\n    .build();\n\n// making request\nIBMAssistantV1Models.Intent intent = assistant.createIntent(options);\nSystem.debug(intent);\n```\n\nThe manner of instantiating and using services should be consistent no matter which you decide to use, which should make it easy to explore the many capabilities Watson services have to offer.\n\n## Request and response headers\n\nThe SDK supports sending custom headers with any request as well as parsing headers that are returned by the service.\n\nTo send request headers, simply add them as a property when building up your `Options` model. Here's an example in the Discovery service:\n\n```java\nIBMDiscoveryV1Models.QueryOptions options =\n  new IBMDiscoveryV1Models.QueryOptionsBuilder()\n    .environmentId('\u003cenvironment_id\u003e')\n    .collectionId('\u003ccollection_id\u003e')\n    .naturalLanguageQuery('Articles about the Boston Celtics')\n    .addHeader('Custon-Header', 'custom_value') // custom header added here\n    .build();\n```\n\nTo get headers returned by the service, call the `getHeaders()` method on a response model. This is what it looks like to get the headers returned after making the above call:\n\n```java\nIBMDiscoveryV1Models.QueryResponse response = discovery.query(options);\nMap\u003cString, String\u003e responseHeaders = response.getHeaders();\n```\n\n## Transaction IDs\n\nEvery SDK call returns a response with a transaction ID in the `x-global-transaction-id` header. This transaction ID is useful for troubleshooting and accessing relevant logs from your service instance.\n\n```java\nIBMWatsonAuthenticator authenticator = new IBMWatsonIAMAuthenticator('API_KEY');\nIBMAssistantV1 service = new IBMAssistantV1('2019-02-28', authenticator);\n\nIBMAssistantV1Models.CreateIntentOptions options =\n  new IBMAssistantV1Models.ListWorkspacesOptionsBuilder().build();\nIBMAssistantV1Models.WorkspaceCollection\u003e response;\n\ntry {\n  // In a successful case, you can grab the ID with the following code.\n  response = service.listWorkspaces(options);\n\tString transactionId = response.getHeaders().get('x-global-transaction-id');\n} catch (IBMWatsonServiceExceptions.ServiceException e) {\n  // This is how you get the ID from a failed request.\n  // Make sure to use the IBMWatsonServiceExceptions.ServiceException class\n  // or one of its subclasses!\n  String transactionId = e.getResponse().getHeader('x-global-transaction-id');\n}\n```\n\n## Using the SDK with Lightning\n\nThe Watson Salesforce SDK models are Lightning-ready, meaning that you can access model properties through Javascript for your Lightning apps. Everything should work as expected, but it's important to note that there are two ways to go about dealing with dynamic models through Javascript. These models are ones which may have properties unknown until runtime and which extend `IBMWatsonDynamicModel`.\n\n### Using the `additionalProperties` object\n\nDynamic models have an extra \"AuraEnabled\" property called `additionalProperties`, which is a map that holds all of the dynamic properties returned with the model. If you're dealing with a dynamic model in your Javascript code and want to access any dynamic properties, you can do the following:\n\n```javascript\naction.setCallback(this, function(response) {\n  var resp = response.getReturnValue(); // resp is a dynamic model\n  console.log(resp.additionalProperties[\"enriched_text\"][\"concepts\"][0][\"text\"]);\n});\n$A.enqueueAction(action);\n```\n\nAny properties within the `additionalProperties` object can be accessed exactly like a generic Javascript object.\n\n### Using the model string representation\n\nIf going through the `additionalProperties` object is undesired for any reason, you can still access the dynamic properties as top-level properties with a small workaround. All models in the SDK override the `toString()` method to output the models as pretty-printed JSON with the additional properties brought up to the top level. Therefore, if you tweak your server-side controller to return the string representation instead of the model object, as follows:\n\n```apex\npublic class ServerSideController {\n  @AuraEnabled\n  public static String query(String environmentId, String collectionId) {\n    IBMDiscoveryV1 discovery = new IBMDiscoveryV1('2019-04-30');\n    IBMDiscoveryV1Models.QueryOptions options = new IBMDiscoveryV1Models.QueryOptionsBuilder(environmentId, collectionId)\n      .naturalLanguageQuery('example query')\n      .build();\n    IBMDiscoveryV1Models.QueryResponse response = discovery.query(options);\n\n    // IMPORTANT: return the string instead of the model\n    return response.toString();\n  }\n}\n```\n\nyou can use `JSON.parse()` to access the whole object as a generic JSON object. Here is an example of accessing the same property in Javascript using this aternate method:\n\n```javascript\naction.setCallback(this, function(response) {\n  var resp = response.getReturnValue(); // resp is now the string representation of our dynamic model\n  console.log(JSON.parse(resp)[\"enriched_text\"][\"concepts\"][0][\"text\"]);\n});\n$A.enqueueAction(action);\n```\n\nBoth methods shown above will print out the same information.\n\n## WebSocket support\nBoth the Text to Speech and Speech to Text services have API endpoints which support the use of WebSockets. However, the use of WebSockets are not supported natively by Apex. If you would like to take advantage of this functionality, the recommendation would be to leverage the [Watson Speech Javascript SDK](https://github.com/watson-developer-cloud/speech-javascript-sdk).\n\nThe above library adds minimal overhead and will allow for the use of WebSockets. Also, being Javascript, this SDK can integrate smoothly with Lightning apps and be used alongside the Salesforce SDK.\n\n## ICP/Cloud Pak for Data\nIf you're using this SDK to interact with a service on IBM Cloud Private (ICP) or Cloud Pak for Data (CP4D), you'll need to add your self-signed certificate to your Salesforce organization. You can do this in the Certificate and Key Management section of the security settings.\n\n## Functional tests\n\nThe `force-app/main/test` folder contains the example calls for each service. These examples are used for functional testing of services. Developers can use them for reference and testing the installed SDK.\n\n## Featured projects\nWe'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it.\n\n## Contributing\n\nIf you're interested in helping to make this project better, see [Contributing.md](.github/Contributing.md).\n\n## License\n\nThis library is licensed under the MIT license. Full license text is\navailable in [LICENSE](LICENSE).\n\n[ibm-cloud-onboarding]: http://cloud.ibm.com/registration?target=/developer/watson\u0026cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-SalesForce\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwatson-developer-cloud%2Fsalesforce-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwatson-developer-cloud%2Fsalesforce-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwatson-developer-cloud%2Fsalesforce-sdk/lists"}