Using Salesforce Named Credentials for Chat GPT API

Using Salesforce Named Credentials for Chat GPT API

2023, May 31    

In Summer’23 Salesforce has released an update to Named Credentials feature to make external integrations authentication simpler and more secure. In this article we will explore how to use this feature with API Key authentication. Given all the excitement around OpenAI and ChatGPT, will use it as an example.

At high level will build a Lightning Web Component that can send a prompt to send requests to OpenAI API and render a response. We will use Summer’23 Named Credentials to authenticate to OpenAI with API Key.

Things we need to get started

  • Salesforce Developer organization
  • OpenAI account
  • Generated OpenAI API Key

For Salesforce development in this example I will use a basic scratch org. This will also keep my changes in source code tracking.

Temporary free Open AI account will do for this example.

Resources: giving credit to Ross Belmont for sharing his detailed article named-creds-api-key that helped me to connect the dots.

Named Credentials

This secure management of credential secrets consist of two parts,

  • Named Credentials
  • External Credentials

External credentials is what really stores the secrets securely. Once saved nobody can read or view these secrets, only reference them and use them in Apex or External services. External credentials must be created before Named Credentials. Named Credentials will use this External Credentials during configuration. External Credentials

Named Credentials is linked as parent to External Credentials, and provides configuration on how these credentials will be used in authentication flows. There are several options that control how authorization headers or custom headers are created. Named Credentials

For our use case we need to generate Authorization headers for HTTP/S REST API requests to OpenAI using API Key. Two values we need to select when creating Named Credential record are

  • Generate Authorization Headers
  • Allow Formulas in HTTP headers

The reason we need formula here is to generate Authorization header without directly typing API Key in open text here. Instead we are using parameter to get secure API Key stored in external credential. Custom Header formula

Setup External Credentials

For the purpose of this demo we need to use API Key for authentication. We will set up external credentials for use with API key, will choose the following:

  • Label - GCAI API Credential
  • Name - GCAIAPICredential (no spaces or dash)
  • Authentication protocol as Custom
  • Save

Next step is to add Principal. Select a Parameter name as API Principal, this can be any arbitrary text. The next step after this is very important! Add Authentication Parameters is where the API Key will be saved. Add API Key

It is possible to have several such credential parameters for use with different environments (DEV, TEST, PROD). In this case we have only one. Click Add 1st parameter and enter name and value. Name will use OpenAIAPIKey, it is best to use names as one word no spaces or special characters. Will need to remember this because it will be used in a Formula later on to set up Named Credentials. The value needs to enter OpenAI API Key and save. Once saved the key is encrypted and secure. We can change these values later if we need to use new key or rotate credentials for security reasons.

Using credentials in APEX

After we have our API key stored secure in named credentials we can use it in APEX code or Use External Service with Flow.

Here is an example of POST callout

...
private final static String SF_NAMED_CREDENTIAL = 'callout:GCAI_API_KEY';
 
public static HttpResponse calloutPostService(String payload, String endpoint){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(SF_NAMED_CREDENTIAL + endpoint);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json');        

        System.debug('## GPT POST REQUEST: '+payload);
        // Set the body as a JSON object
        request.setBody(payload);
        HttpResponse response = http.send(request);
        // Parse the JSON response
        System.debug('## POST RESPONSE CODE: ' + response.getStatusCode() + ' Status: ' + response.getStatus());
        System.debug('## POST RESPONSE DATA: ' + response.getBody());
        return response;
    }

Example of a GET callout.

private final static String SF_NAMED_CREDENTIAL = 'callout:GCAI_API_KEY';

public static HttpResponse calloutGetService(String endpoint){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(SF_NAMED_CREDENTIAL + endpoint);
        request.setMethod('GET');
        request.setHeader('Content-Type', 'application/json');        

        HttpResponse response = http.send(request);
        // Parse the JSON response
        System.debug('## GET RESPONSE CODE: ' + response.getStatusCode() + ' Status: ' + response.getStatus());
        System.debug('## GET RESPONSE DATA: ' + response.getBody());
        return response;
    }

Conclusion

For complete documentation and more details refer to this AI Playground.

Source code can be found in this GitHub repository