Translate

Tuesday, April 5, 2022

Golang - Query Salesforce by using the Salesforce API

I've been learning how to query Salesforce by using the Salesforce API. Here is a simple example that uses the Salesforce query from my last post to query a custom object for values from two related tables. I am using the simpleforce package.

1 - Function to connect to Salesforce:


var (
	SfURL      = "https://mysite.my.salesforce.com/" //Custom or instance URL, for example, 'https://na01.salesforce.com/'
	SfUser     = "me@email.org"           //User name of the Salesforce account                                                                                    //"Username of the Salesforce account."
	SfPassword = "MyPassword"                         //Password of the Salesforce account.
	SfToken    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"            //Security token, could be omitted if Trusted IP is configured.
)

func CreateClient() *simpleforce.Client {
	client := simpleforce.NewClient(SfURL, simpleforce.DefaultClientID, simpleforce.DefaultAPIVersion)
	if client == nil {
		// handle the error
		fmt.Println("Unable to create client.")
		return nil
	}

	err := client.LoginPassword(SfUser, SfPassword, SfToken)
	if err != nil {
		// handle the error
		fmt.Println("Unable to log in.")
		fmt.Println(err)
		return nil
	} else {
		fmt.Println("SF logged in!")
	}
	// Do some other stuff with the client instance if needed.

	return client
}


2 - Function to query Salesforce. I pass in the query from my last blog post, "Select Project__r.Name, Geographic_Area__r.Country_Code__c from Project_Geographic_Area__c"

//Query Salesforce using the passed in SOQL script
func GetByS(strQ string) {
	client := CreateClient()
	result, err := client.Query(strQ) // Note: for Tooling API, use client.Tooling().Query(q)
	if err != nil {
		// handle the error
		fmt.Println(err)
		return
	}

	for _, record := range result.Records {
		// access the record as SObjects.
		fmt.Println(record)
		//Example 1
		ifvP := record.InterfaceField("Project__r") //get the interface
		strP := ifvP.(map[string]interface{})["Name"] //get the string
		fmt.Println("Project:", strP)
		//Eample 2
		strC := record.InterfaceField("Geographic_Area__r").(map[string]interface{})["Country_Code__c"] //get the string from the interface
		fmt.Println("Country", strC)
	}
}


1 comment:

Thank you for commenting!