May 12, 2025
Today, businesses want to work faster and give customers more personal, helpful experiences. Salesforce is a popular tool that helps companies manage customer data and run their day-to-day work. But what if you could make Salesforce even smarter?
That’s where ChatGPT comes in — an AI tool from OpenAI that can talk like a human, write emails, answer questions, and more. By connecting ChatGPT to Salesforce, you can save time, automate tasks, and make your system more intelligent.
In this blog, we’ll show you how to connect Salesforce with ChatGPT using the OpenAI API and Apex.
Salesforce GPT Integration
)
Now that you have your ChatGPT API key, let’s store it securely in Salesforce using a Custom Label. This allows you to manage the key without hardcoding it in Apex.
ChatGPT Key
ChatGPT
let’s create an Apex class that sends a request to ChatGPT and gets a response using the API key stored in your custom label.
For this, Create an apex class called ChatGPTIntegration and paste the below code into it.
public class ChatGPTIntegration {public static void getResponse(String input) {String key = Label.ChatGPT_Key;String body = '{"model": "gpt-4.1", "input": "'+ input +'"}';
HttpRequest req = new HttpRequest();req.setMethod('POST');req.setEndpoint('https://api.openai.com/v1/responses');req.setHeader('Content-Type', 'application/json');req.setHeader('Authorization', 'Bearer '+ key);req.setBody(body);
Http http = new Http();HttpResponse res = http.send(req);Map<String, Object> response = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());List<Object> outputs = (List<Object>) response.get('output');List<Map<String, Object>> outputsMap = new List<Map<String, Object>>();for(Object obj : outputs) {Map<String, Object> content = (Map<String, Object>) obj;outputsMap.add(content);}List<Object> contents = (List<Object>) outputsMap[0].get('content');List<Map<String, Object>> contentsMap = new List<Map<String, Object>>();for(Object obj : contents) {Map<String, Object> content = (Map<String, Object>) obj;contentsMap.add(content);}String text = (String) contentsMap[0].get('text');System.debug('Output => '+text);}}
String input = 'Write a one-sentence bedtime story about a unicorn.';
ChatGPTIntegration.getResponse(input);
Press the Execute button.