如何通过API从第三方Web应用在Salesforce中创建Case
Hey there! I’ve built multiple integrations between external web apps and Salesforce Cases, so I can walk you through the most reliable approach using Salesforce’s REST API. Here’s a step-by-step breakdown:
1. First: Authenticate Your Web App with Salesforce
You’ll need a valid access token to make API calls. For server-side web apps, the OAuth 2.0 Client Credentials Flow is the go-to choice (since this is a server-to-server integration without direct user context). If your app acts on behalf of a logged-in user, use the Authorization Code Flow instead.
To get an access token:
- Send a
POSTrequest tohttps://<your-salesforce-domain>/services/oauth2/token - Include these form-data parameters:
grant_type:client_credentialsclient_id: Your Connected App’s Consumer Keyclient_secret: Your Connected App’s Consumer Secret
The response will include an access_token and instance_url (use this to build your API endpoints).
2. The REST Endpoint to Create a Case
Once authenticated, use this endpoint to create a Case record:
POST /services/data/vXX.X/sobjects/Case/
Replace vXX.X with a recent stable API version (e.g., v59.0 — pick one from Salesforce’s supported stable versions to avoid breaking changes).
3. Example Request Payload & Code
The request body needs to be JSON, containing at least the required fields for your Salesforce Case object (common ones are Subject and Description). You can also add optional fields like Origin (to mark the source as your web app) or related record IDs (e.g., ContactId if you’re linking the case to a known user in Salesforce).
Python Example
import requests # Step 1: Fetch access token auth_url = "https://your-salesforce-instance.my.salesforce.com/services/oauth2/token" auth_data = { "grant_type": "client_credentials", "client_id": "YOUR_CONSUMER_KEY", "client_secret": "YOUR_CONSUMER_SECRET" } auth_response = requests.post(auth_url, data=auth_data) auth_result = auth_response.json() access_token = auth_result["access_token"] instance_url = auth_result["instance_url"] # Step 2: Create Case case_endpoint = f"{instance_url}/services/data/v59.0/sobjects/Case/" case_payload = { "Subject": "Web App Login Issue", "Description": "User John Doe reported unable to access the dashboard after entering valid credentials.", "Origin": "Web", "ContactId": "0031I000001abcXYZ" # Replace with actual Contact ID if available } headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } case_response = requests.post(case_endpoint, json=case_payload, headers=headers) if case_response.status_code == 201: print(f"Case created successfully! Case ID: {case_response.json()['id']}") else: print(f"Error creating Case: {case_response.json()}")
JavaScript (Node.js) Example
const axios = require('axios'); // Step 1: Authenticate const authUrl = 'https://your-salesforce-instance.my.salesforce.com/services/oauth2/token'; const authData = new URLSearchParams({ grant_type: 'client_credentials', client_id: 'YOUR_CONSUMER_KEY', client_secret: 'YOUR_CONSUMER_SECRET' }); axios.post(authUrl, authData) .then(authRes => { const accessToken = authRes.data.access_token; const instanceUrl = authRes.data.instance_url; // Step 2: Create Case const caseEndpoint = `${instanceUrl}/services/data/v59.0/sobjects/Case/`; const casePayload = { Subject: 'Web App Feature Request', Description: 'User wants to export data as CSV from the profile page.', Origin: 'Web' }; return axios.post(caseEndpoint, casePayload, { headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }); }) .then(caseRes => { console.log('Case created successfully! Case ID:', caseRes.data.id); }) .catch(err => { console.error('Error:', err.response.data); });
4. Critical Notes to Avoid Issues
- Check Required Fields: Your Salesforce org might have custom required fields for Cases (e.g.,
Priority). Use theDescribe Caseendpoint (GET /services/data/vXX.X/sobjects/Case/describe) to get a full list of fields and their requirements. - Connected App Permissions: Ensure your Connected App has the
Modify All DataorCreate Casespermission (assign a relevant Permission Set to the Connected App’s associated user). - Error Handling: Always handle non-201 status codes. Common errors include missing required fields, invalid record IDs, or insufficient permissions.
- API Version: Stick to a stable API version (not the absolute latest beta) to avoid unexpected breaking changes.
内容的提问来源于stack exchange,提问作者George Ortiz

