go_salesforce_api_client

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2026 License: MIT Imports: 10 Imported by: 0

README

🚀 Go Salesforce API Client

A lightweight, fast, and developer-friendly Go client for interacting with Salesforce APIs. This library provides easy access to CRUD operations, SOQL queries, Tooling API, and authentication.

🎯 Features

Easy Authentication: Supports OAuth2 Password Flow and Client Credentials Flow. ✅ SOQL Query Support: Execute complex SOQL queries with ease. ✅ CRUD Operations: Perform create, read, update, delete on any Salesforce object. ✅ Tooling API Access: Interact with metadata and developer tooling API. ✅ Bulk Query API Support: Efficiently fetch large datasets using Salesforce Bulk Query Jobs with automatic pagination. ✅ Well-Tested: 90%+ test coverage with httptest-based mocks. ✅ Lightweight & Fast: Minimal dependencies for blazing-fast performance.

📦 Installation

go install github.com/MASA-JAPAN/go-salesforce-api-client

🚀 Quick Start

1️⃣ Authenticate with Salesforce
// Initialize authentication details
auth := go_salesforce_api_client.Auth{
    ClientID:     "your_client_id",
    ClientSecret: "your_client_secret",
    TokenURL:     "https://your-domain.my.salesforce.com/services/oauth2/token",
}

// Authenticate and retrieve an access token
client, err := auth.AuthenticateClientCredentials()
if err != nil {
    log.Fatalf("Authentication failed: %v", err)
}
2️⃣ Query Salesforce Data
// Define the SOQL query
soql := "SELECT Id, Name FROM Account LIMIT 10"

// Execute the query
queryResponse, err := client.Query(soql)
if err != nil {
    log.Fatalf("Query failed: %v", err)
}

// Print query results
fmt.Println("Query Results:")
for _, record := range queryResponse.Records {
    fmt.Printf("ID: %s, Name: %s\n", record["Id"], record["Name"])
}
3️⃣ Create a New Records
records := []map[string]interface{}{
    {"Name": "Sample Corp A"},
    {"Name": "Sample Corp B"},
    {"Name": "Sample Corp C"},
}

response, err := client.CreateRecords("Account", records)
if err != nil {
    fmt.Println("Error creating records:", err)
    return
}

fmt.Println("Record Creation Response:", response)
4️⃣ Update a Records
records := []map[string]interface{}{
    {"Id": "001IR00001ulZ5TYAU", "Name": "Updated Sample Corp A"},
    {"Id": "001IR00001ulZ5UYAU", "Name": "Updated Sample Corp B"},
    {"Id": "001IR00001ulZ5VYAU", "Name": "Updated Sample Corp C"},
}

err = client.UpdateRecords("Account", records)
if err != nil {
    fmt.Println("Error updating records:", err)
    return
}
5️⃣ Delete a Record
ids := []string{"001IR00001ulZ5YYAU", "001IR00001ulZ5ZYAU", "001IR00001ulZ5aYAE"}

err = client.DeleteRecords("Account", ids)
if err != nil {
    fmt.Println("Error updating records:", err)
    return
}
6️⃣ Deploy Metadata
// Create deployment ZIP (package.xml + metadata files)
zipBase64 := createDeploymentZip() // Your function to create base64-encoded ZIP

// Configure deploy options
options := go_salesforce_api_client.MetadataDeployOptions{
    CheckOnly:       false, // Set true for validation-only
    RollbackOnError: true,
    SinglePackage:   true,
    TestLevel:       "NoTestRun",
}

// Initiate deployment
asyncResult, err := client.DeployMetadata(zipBase64, options)
if err != nil {
    fmt.Println("Deploy failed:", err)
    return
}

// Poll for completion
for {
    status, err := client.CheckDeployStatus(asyncResult.ID)
    if err != nil {
        fmt.Println("Error checking status:", err)
        return
    }

    fmt.Printf("Status: %s (%d/%d components)\n",
        status.Status,
        status.NumberComponentsDeployed,
        status.NumberComponentsTotal)

    if status.Done {
        if status.Success {
            fmt.Println("Deploy succeeded!")
        } else {
            // Print failures
            for _, failure := range status.Details.ComponentFailures {
                fmt.Printf("%s: %s [Line %d]\n",
                    failure.FileName,
                    failure.Problem,
                    failure.LineNumber)
            }
        }
        break
    }

    time.Sleep(5 * time.Second)
}
7️⃣ Retrieve Metadata
// Define package manifest
manifest := `<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
        <name>ApexClass</name>
    </types>
    <version>58.0</version>
</Package>`

// Configure retrieve options
options := go_salesforce_api_client.MetadataRetrieveOptions{
    ApiVersion:        "58.0",
    SinglePackage:     true,
    UnpackageManifest: manifest,
}

// Initiate retrieve
asyncResult, err := client.RetrieveMetadata(options)
if err != nil {
    fmt.Println("Retrieve failed:", err)
    return
}

// Poll for completion
for {
    status, err := client.CheckRetrieveStatus(asyncResult.ID)
    if err != nil {
        fmt.Println("Error checking status:", err)
        return
    }

    if status.Done {
        if status.Success {
            // Save ZIP file
            zipData, _ := base64.StdEncoding.DecodeString(status.ZipFileBase64)
            os.WriteFile("metadata.zip", zipData, 0644)
            fmt.Println("Metadata retrieved successfully!")
        }
        break
    }

    time.Sleep(5 * time.Second)
}

📌 Supported APIs

  • Authentication (OAuth2)
  • SOQL Queries
  • CRUD Operations
  • Tooling API
  • Bulk Query API
  • Composite Requests
  • Limits API (Monitor API usage)
  • Metadata API (Deploy & Retrieve metadata packages)

📜 License

MIT License © 2025 MASA-JAPAN

⭐ Show Your Support

If you found this useful, please star this repository ⭐ and share it with others!


🚀 Go Salesforce API Client - Making Salesforce Development Easier for Go Developers!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSOAPFault       = errors.New("SOAP fault occurred")
	ErrInvalidSession  = errors.New("invalid session ID")
	ErrDeployFailed    = errors.New("deployment failed")
	ErrRetrieveFailed  = errors.New("retrieve failed")
	ErrInvalidZip      = errors.New("invalid ZIP file")
	ErrInvalidManifest = errors.New("invalid package manifest")
)

Error variables

Functions

This section is empty.

Types

type Auth

type Auth struct {
	ClientID     string
	ClientSecret string
	Username     string
	Password     string
	TokenURL     string
}

Auth handles authentication with Salesforce

func (*Auth) AuthenticateClientCredentials

func (a *Auth) AuthenticateClientCredentials() (*Client, error)

AuthenticateClientCredentials performs Client Credentials OAuth flow

func (*Auth) AuthenticatePassword

func (a *Auth) AuthenticatePassword() (*Client, error)

AuthenticatePassword performs an OAuth login and retrieves an access token

type Client

type Client struct {
	AccessToken string `json:"access_token"`
	InstanceURL string `json:"instance_url"`
	TokenType   string `json:"token_type"`
	IssuedAt    string `json:"issued_at"`
}

Client represents the Salesforce OAuth token response

func (*Client) AbortJobQuery added in v1.1.0

func (c *Client) AbortJobQuery(jobID string) error

func (*Client) CancelDeploy added in v1.2.0

func (c *Client) CancelDeploy(asyncProcessID string) (*MetadataAsyncResult, error)

CancelDeploy cancels an in-progress deployment

func (*Client) CheckDeployStatus added in v1.2.0

func (c *Client) CheckDeployStatus(asyncProcessID string) (*MetadataDeployResult, error)

CheckDeployStatus checks the status of an asynchronous deployment

func (*Client) CheckRetrieveStatus added in v1.2.0

func (c *Client) CheckRetrieveStatus(asyncProcessID string) (*MetadataRetrieveResult, error)

CheckRetrieveStatus checks the status of an asynchronous retrieval

func (*Client) CreateCustomField added in v1.1.0

func (c *Client) CreateCustomField(fieldData CustomField) (map[string]interface{}, error)

CreateCustomField creates a new custom field in Salesforce using the Tooling API

func (*Client) CreateJobQuery added in v1.1.0

func (c *Client) CreateJobQuery(query string) (*JobQueryResponse, error)

CreateJobQuery initiates a Bulk Query Job in Salesforce

func (*Client) CreateRecord

func (c *Client) CreateRecord(objectType string, record map[string]interface{}) (*SobjectResponse, error)

CreateRecord creates a new Salesforce record

func (*Client) CreateRecords

func (c *Client) CreateRecords(objectType string, records []map[string]interface{}) ([]CompositeResponse, error)

CreateRecords creates multiple Salesforce records

func (*Client) DeleteJobQuery added in v1.1.0

func (c *Client) DeleteJobQuery(jobID string) error

DeleteJobQuery permanently removes a Bulk Query Job in Salesforce

func (*Client) DeleteRecord

func (c *Client) DeleteRecord(objectType, recordID string) error

DeleteRecord deletes a Salesforce record by ID

func (*Client) DeleteRecords

func (c *Client) DeleteRecords(objectType string, recordIDs []string) error

DeleteRecords deletes multiple Salesforce records

func (*Client) DeployMetadata added in v1.2.0

func (c *Client) DeployMetadata(zipFileBase64 string, options MetadataDeployOptions) (*MetadataAsyncResult, error)

DeployMetadata initiates an asynchronous metadata deployment

func (*Client) DescribeSObject

func (c *Client) DescribeSObject(objectType string) (map[string]interface{}, error)

DescribeSObject retrieves metadata for a given Salesforce object

func (*Client) GetJobQuery added in v1.1.0

func (c *Client) GetJobQuery(jobID string) (*JobQueryResponse, error)

GetJobQuery retrieves the status and details of a Bulk Query Job in Salesforce

func (*Client) GetJobQueryResults added in v1.1.0

func (c *Client) GetJobQueryResults(jobID, queryLocator string, maxRecords int) (string, string, error)

GetJobQueryResults retrieves the job query results using pagination and maxRecords

func (*Client) GetJobQueryResultsParsed added in v1.1.0

func (c *Client) GetJobQueryResultsParsed(jobID, queryLocator string, maxRecords int) ([]JobQueryResult, string, error)

GetJobQueryResultsParsed retrieves job query results and converts them into a structured format

func (*Client) GetLimits

func (c *Client) GetLimits() (LimitsResponse, error)

GetLimits retrieves the API usage limits from Salesforce

func (*Client) GetRecord

func (c *Client) GetRecord(objectType, recordID string) (map[string]interface{}, error)

GetRecord retrieves a Salesforce record by ID

func (*Client) GetRecordCounts

func (c *Client) GetRecordCounts(objects []string) (CountResponse, error)

GetRecordCounts retrieves the record count for specified Salesforce objects

func (*Client) Query

func (c *Client) Query(soql string) (*QueryResponse, error)

Query executes a SOQL query against Salesforce

func (*Client) QueryToolingAPI

func (c *Client) QueryToolingAPI(soql string) (*ToolingResponse, error)

QueryToolingAPI executes a SOQL query against the Salesforce Tooling API

func (*Client) RetrieveMetadata added in v1.2.0

func (c *Client) RetrieveMetadata(options MetadataRetrieveOptions) (*MetadataAsyncResult, error)

RetrieveMetadata initiates an asynchronous metadata retrieval

func (*Client) UpdateRecord

func (c *Client) UpdateRecord(objectType, recordID string, updates map[string]interface{}) error

UpdateRecord updates a Salesforce record by ID

func (*Client) UpdateRecords

func (c *Client) UpdateRecords(objectType string, records []map[string]interface{}) error

UpdateRecords updates multiple Salesforce records

type CodeCoverageResult added in v1.2.0

type CodeCoverageResult struct {
	ID                     string
	LocationsNotCovered    []CodeLocation
	Name                   string
	Namespace              string
	NumLocations           int
	NumLocationsNotCovered int
	Type                   string
}

CodeCoverageResult represents code coverage for a class

type CodeLocation added in v1.2.0

type CodeLocation struct {
	Column        int
	Line          int
	NumExecutions int
	Time          float64
}

CodeLocation represents a code location

type ComponentFailure added in v1.2.0

type ComponentFailure struct {
	Changed       bool
	Created       bool
	Deleted       bool
	FileName      string
	FullName      string
	ComponentType string
	Problem       string
	ProblemType   string
	LineNumber    int
	ColumnNumber  int
	Success       bool
}

ComponentFailure represents failed component

type ComponentSuccess added in v1.2.0

type ComponentSuccess struct {
	Changed       bool
	Created       bool
	Deleted       bool
	FileName      string
	FullName      string
	ComponentType string
	Success       bool
}

ComponentSuccess represents successful component

type CompositeResponse

type CompositeResponse struct {
	ID      string `json:"id"`
	Success bool   `json:"success"`
	Errors  []any  `json:"errors"`
}

CompositeResponse represents the generic Salesforce API response

type CountResponse

type CountResponse map[string]interface{}

CountResponse represents the response structure from Salesforce record count API

type CustomField added in v1.1.0

type CustomField struct {
	FullName string `json:"FullName"`
	Metadata struct {
		Label  string `json:"label"`
		Type   string `json:"type"`
		Length int    `json:"length,omitempty"`
	} `json:"Metadata"`
}

CustomField represents the structure for creating a Salesforce custom field

type DeployDetails added in v1.2.0

type DeployDetails struct {
	ComponentSuccesses []ComponentSuccess
	ComponentFailures  []ComponentFailure
	RunTestResult      *RunTestResult
}

DeployDetails contains detailed deploy results

type FileProperty added in v1.2.0

type FileProperty struct {
	CreatedByID        string
	CreatedByName      string
	CreatedDate        string
	FileName           string
	FullName           string
	ID                 string
	LastModifiedByID   string
	LastModifiedByName string
	LastModifiedDate   string
	ManageableState    string
	NamespacePrefix    string
	Type               string
}

FileProperty represents metadata about a retrieved file

type JobQueryResponse added in v1.1.0

type JobQueryResponse struct {
	ID     string `json:"id"`
	State  string `json:"state"`
	Object string `json:"object"`
}

JobQueryResponse represents the response from Salesforce Bulk Query API

type JobQueryResult added in v1.1.0

type JobQueryResult map[string]string

JobQueryResult represents a single row in the job query results.

type LimitsResponse

type LimitsResponse map[string]interface{}

LimitsResponse represents the response structure from Salesforce limits API

type MetadataAsyncResult added in v1.2.0

type MetadataAsyncResult struct {
	ID              string
	Done            bool
	State           string
	StateDetail     string
	StatusCode      string
	ErrorMessage    string
	ErrorStatusCode string
}

MetadataAsyncResult represents async operation status

type MetadataDeployOptions added in v1.2.0

type MetadataDeployOptions struct {
	AllowMissingFiles bool
	AutoUpdatePackage bool
	CheckOnly         bool // Validation deploy only
	IgnoreWarnings    bool
	PerformRetrieve   bool
	PurgeOnDelete     bool
	RollbackOnError   bool
	RunTests          []string // Test classes to run
	SinglePackage     bool
	TestLevel         string // NoTestRun, RunSpecifiedTests, RunLocalTests, RunAllTestsInOrg
}

MetadataDeployOptions configures deploy behavior

type MetadataDeployResult added in v1.2.0

type MetadataDeployResult struct {
	CheckOnly                bool
	CompletedDate            string
	CreatedDate              string
	Details                  *DeployDetails
	Done                     bool
	ErrorMessage             string
	ID                       string
	IgnoreWarnings           bool
	NumberComponentErrors    int
	NumberComponentsDeployed int
	NumberComponentsTotal    int
	NumberTestErrors         int
	NumberTestsCompleted     int
	NumberTestsTotal         int
	RollbackOnError          bool
	RunTestsEnabled          bool
	StartDate                string
	Status                   string
	Success                  bool
}

MetadataDeployResult represents deploy operation result

type MetadataRetrieveOptions added in v1.2.0

type MetadataRetrieveOptions struct {
	ApiVersion        string
	PackageNames      []string
	SinglePackage     bool
	SpecificFiles     []string
	UnpackageManifest string // XML manifest content
}

MetadataRetrieveOptions configures retrieve behavior

type MetadataRetrieveResult added in v1.2.0

type MetadataRetrieveResult struct {
	Done            bool
	ErrorMessage    string
	ErrorStatusCode string
	FileProperties  []FileProperty
	ID              string
	Messages        []RetrieveMessage
	State           string
	Status          string
	Success         bool
	ZipFileBase64   string
}

MetadataRetrieveResult represents retrieve operation result

type QueryResponse

type QueryResponse struct {
	TotalSize int              `json:"totalSize"`
	Done      bool             `json:"done"`
	Records   []map[string]any `json:"records"`
}

QueryResponse represents the response structure from Salesforce SOQL query

type RetrieveMessage added in v1.2.0

type RetrieveMessage struct {
	FileName string
	Problem  string
}

RetrieveMessage represents a retrieve status message

type RunTestResult added in v1.2.0

type RunTestResult struct {
	NumFailures  int
	NumTestsRun  int
	TotalTime    float64
	Successes    []TestSuccess
	Failures     []TestFailure
	CodeCoverage []CodeCoverageResult
}

RunTestResult contains test execution results

type SobjectResponse

type SobjectResponse struct {
	ID      string `json:"id"`
	Success bool   `json:"success"`
	Errors  []any  `json:"errors"`
}

SobjectResponse represents the generic Salesforce API response

type TestFailure added in v1.2.0

type TestFailure struct {
	ID         string
	Message    string
	MethodName string
	Name       string
	Namespace  string
	StackTrace string
	Time       float64
	Type       string
}

TestFailure represents failed test

type TestSuccess added in v1.2.0

type TestSuccess struct {
	ID         string
	MethodName string
	Name       string
	Namespace  string
	Time       float64
}

TestSuccess represents passed test

type ToolingResponse

type ToolingResponse struct {
	TotalSize int                      `json:"totalSize"`
	Done      bool                     `json:"done"`
	Records   []map[string]interface{} `json:"records"`
}

ToolingResponse represents the response structure from Salesforce tooling API

Directories

Path Synopsis
examples
auth command
composite command
count command
jobQuery command
limit command
metadata command
query command
sobject command
tooling command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL