After reading this article to the end, you will be able to:
--Set up Salesforce API (enable OAuth settings) --Get Salesforce data with Python, Java, Shell Script --Implementing REST web services in Salesforce Apex
Sample code
python_sfdc_get_user.py
sf = Salesforce(username=USERNAME, password=PASSWORD,
security_token=SECURITY_TOKEN, sandbox=False)
res = sf.query(
'SELECT Id, Name, LastLoginDate FROM User WHERE Name =\'nsuhara\'')
print(json.dumps(res, indent=4))
Execution result
python_result.json
{
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "User",
"url": "/services/data/v38.0/sobjects/User/0056F000006StK9QAK"
},
"Id": "0056F000006StK9QAK",
"Name": "nsuhara",
"LastLoginDate": "2019-05-18T13:07:00.000+0000"
}
]
}
-SFDC REST API Developer's Guide
environment | Ver. | Note |
---|---|---|
macOS Mojave | 10.14.4 | OS |
Salesforce | Spring'19 | SaaS |
Python | 3.7.3 | Python |
simple-salesforce | 0.74.2 | Python |
requests | 2.22.0 | Python |
Java | 1.8.0_192 | Java |
httpclient | 4.5.6 | Java |
json | 20180813 | Java |
jackson-databind | 2.9.8 | Java |
I think that understanding will deepen if you read while actually following the implementation contents and source code. Please use it by all means.
Settings> Create> Applications> Connected Applications> Click New
item name | Set value |
---|---|
Connected application name | Sample |
API reference name | Sample |
Contact Email | [email protected] |
Enable OAuth settings | TRUE |
Callback URL | https://sample.auth0.com/login/callback |
Selected OAuth range | Access to basic information |
Web server flow secret required | TRUE |
`Please wait 2-10 minutes for the changes to take effect on the server before using the connected application. ``
Variable name | Description | Remarks |
---|---|---|
HOST | Production: login.salesforce.com, Sandbox: test.salesforce.com | |
CLIENT_ID | Consumer key | Reference 1 |
CLIENT_SECRET | Consumer secret | Reference 1 |
USERNAME | Salesforce username | |
PASSWORD | Salesforce password | |
SECURITY_TOKEN | Salesforce security token | Reference 2 |
PASSWORD_AND_SECURITY_TOKEN | Salesforce password+Security token |
** (Reference 1) **
** (Ref 2) **
Security tokens can be reissued from My Settings> Personal> Reset My Security Talk
.
shell_script_sfdc_get_user.sh
#!/bin/sh
export HOST='<Parameter reference>'
export CLIENT_ID='<Parameter reference>'
export CLIENT_SECRET='<Parameter reference>'
export USERNAME='<Parameter reference>'
export PASSWORD_AND_SECURITY_TOKEN='<Parameter reference>'
export INSTANCE_URL=`curl -s https://$HOST/services/oauth2/token -d "grant_type=password" -d "client_id=$CLIENT_ID" -d "client_secret=$CLIENT_SECRET" -d "username=$USERNAME" -d "password=$PASSWORD_AND_SECURITY_TOKEN" | awk 'BEGIN{FS="instance_url\":"}{print $2}' | awk 'BEGIN{FS=","}{print $1}' | sed -e 's/\"//g'`
export ACCESS_TOKEN=`curl -s https://$HOST/services/oauth2/token -d "grant_type=password" -d "client_id=$CLIENT_ID" -d "client_secret=$CLIENT_SECRET" -d "username=$USERNAME" -d "password=$PASSWORD_AND_SECURITY_TOKEN" | awk 'BEGIN{FS="access_token\":"}{print $2}' | awk 'BEGIN{FS=","}{print $1}' | sed -e 's/\"//g'`
export SOQL="SELECT+Id,Name,LastLoginDate+FROM+User+WHERE+Name='nsuhara'"
curl $INSTANCE_URL/services/data/v45.0/query?q=$SOQL -H "Authorization: OAuth $ACCESS_TOKEN" -H "X-PrettyPrint:1"
shell_script_result.json
{
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "User",
"url": "/services/data/v45.0/sobjects/User/0056F000006StK9QAK"
},
"Id": "0056F000006StK9QAK",
"Name": "nsuhara",
"LastLoginDate": "2019-05-18T14:04:05.000+0000"
}
]
}
python_sfdc_get_user.py
import json
from simple_salesforce import Salesforce
USERNAME = '<Parameter reference>'
PASSWORD = '<Parameter reference>'
SECURITY_TOKEN = '<Parameter reference>'
def main():
sf = Salesforce(username=USERNAME, password=PASSWORD,
security_token=SECURITY_TOKEN, sandbox=False)
res = sf.query(
'SELECT Id, Name, LastLoginDate FROM User WHERE Name =\'nsuhara\'')
print(json.dumps(res, indent=4))
if __name__ == '__main__':
main()
python_result.json
{
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "User",
"url": "/services/data/v38.0/sobjects/User/0056F000006StK9QAK"
},
"Id": "0056F000006StK9QAK",
"Name": "nsuhara",
"LastLoginDate": "2019-05-18T14:06:19.000+0000"
}
]
}
java_App.java
package rest_api;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
static final String HOST = "<Parameter reference>";
static final String CLIENT_ID = "<Parameter reference>";
static final String CLIENT_SECRET = "<Parameter reference>";
static final String USERNAME = "<Parameter reference>";
static final String PASSWORD_AND_SECURITY_TOKEN = "<Parameter reference>";
static final String GRANT_SERVICE = "/services/oauth2/token?grant_type=password";
public static void main(String[] args) {
String UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36";
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("User-Agent", UA));
HttpClient httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).build();
String loginURL = "https://" + HOST + GRANT_SERVICE + "&client_id=" + CLIENT_ID + "&client_secret="
+ CLIENT_SECRET + "&username=" + USERNAME + "&password=" + PASSWORD_AND_SECURITY_TOKEN;
HttpPost httpPost = new HttpPost(loginURL);
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException cpException) {
// Handle protocol exception
} catch (IOException ioException) {
// Handle system IO exception
}
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("Error authenticating to Force.com: " + statusCode);
// Error is in EntityUtils.toString(response.getEntity())
return;
}
String getResult = null;
try {
getResult = EntityUtils.toString(response.getEntity());
} catch (IOException ioException) {
// Handle system IO exception
}
JSONObject jsonObject = null;
String loginAccessToken = null;
String loginInstanceUrl = null;
try {
jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
loginInstanceUrl = jsonObject.getString("instance_url");
loginAccessToken = jsonObject.getString("access_token");
} catch (JSONException jsonException) {
// Handle JSON exception
}
System.out.println(response.getStatusLine());
httpPost.releaseConnection();
try {
final URIBuilder builder = new URIBuilder(loginInstanceUrl);
final String SOQL = "SELECT Id, Name, LastLoginDate FROM User WHERE Name = \'nsuhara\'";
builder.setPath("/services/data/v45.0/query/").setParameter("q", SOQL);
final HttpGet get = new HttpGet(builder.build());
get.setHeader("Authorization", "Bearer " + loginAccessToken);
final HttpResponse queryResponse = httpClient.execute(get);
ObjectMapper mapper = new ObjectMapper();
final JsonNode queryResults = mapper.readValue(queryResponse.getEntity().getContent(), JsonNode.class);
System.out.println("queryResults:" + queryResults);
} catch (Exception e) {
// Handle exception
}
}
}
java_result.json
{
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "User",
"url": "/services/data/v45.0/sobjects/User/0056F000006StK9QAK"
},
"Id": "0056F000006StK9QAK",
"Name": "nsuhara",
"LastLoginDate": "2019-05-18T14:09:31.000+0000"
}
]
}
apex_SampleRestApi.cls
@RestResource(urlMapping='/sample/restapi/*')
global without sharing class SampleRestApi {
@HttpGet
global static List<User> getUsers() {
return [SELECT Id, Name, LastLoginDate FROM User WHERE Name = 'nsuhara' LIMIT 1];
}
}
Settings> Manage Users> Privilege Set (or Profile)> Edit System Privileges
Settings> Manage Users> Permission Set (or Profile)> Edit Apex Class Access`
python_requests_sfdc.py
import requests
HOST = '<Parameter reference>'
CLIENT_ID = '<Parameter reference>'
CLIENT_SECRET = '<Parameter reference>'
USERNAME = '<Parameter reference>'
PASSWORD_AND_SECURITY_TOKEN = '<Parameter reference>'
def main():
params = {
'grant_type': 'password',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'username': USERNAME,
'password': PASSWORD_AND_SECURITY_TOKEN
}
res_post = requests.post(
'https://{}/services/oauth2/token'.format(HOST), params=params)
access_token = res_post.json().get('access_token')
instance_url = res_post.json().get('instance_url')
services_url = '/services/apexrest/sample/restapi'
headers = {
'Content-type': 'application/json',
'Accept-Encoding': 'gzip',
'Authorization': 'Bearer {}'.format(access_token)
}
res_get = requests.request(method='get', url=instance_url+services_url,
headers=headers, params={'xxx': 'yyy'}, timeout=10)
print(res_get.status_code)
print(res_get.json())
if __name__ == '__main__':
main()
python_result.json
[
{
"attributes": {
"type": "User",
"url": "/services/data/v45.0/sobjects/User/0056F000006StK9QAK"
},
"Id": "0056F000006StK9QAK",
"Name": "nsuhara",
"LastLoginDate": "2019-05-18T14: 11: 22.000+0000"
}
]
Consider the implementation model based on the environment and conditions
No. | Examination conditions | Implementation model | sample |
---|---|---|---|
1 | If you have a package for Salesforce | Implement using a package | Python sample |
2 | When the execution result of SOQL is sufficient | Implement using HTTP request | Shell Script sample,Java sample |
3 | Other than the above | Implement Apex REST Web Services | REST Web Service Implementation Sample |
Recommended Posts