Back

Step by Step Guide to Building a Freshsales Suite API Integration in Go

Aug 15, 20248 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Freshsales Suite API integration with Go? You're in for a treat. This guide will walk you through the process of building a robust integration that'll have you manipulating Freshsales data like a pro. Let's get cracking!

Prerequisites

Before we jump in, make sure you've got:

  • Go installed on your machine (you're a Go dev, so I'm sure you've got this covered)
  • A Freshsales Suite account with an API key (if you don't have one, go grab it from your account settings)
  • Your favorite code editor at the ready

Setting up the project

Let's start by setting up our project structure. Create a new directory for your project and initialize it with Go modules:

mkdir freshsales-integration cd freshsales-integration go mod init freshsales-integration

Authentication

First things first, let's set up authentication. We'll create a reusable HTTP client that includes our API key:

package main import ( "net/http" "time" ) const baseURL = "https://domain.freshsales.io/api" func newClient(apiKey string) *http.Client { return &http.Client{ Timeout: time.Second * 10, Transport: &apiKeyTransport{ APIKey: apiKey, }, } } type apiKeyTransport struct { APIKey string } func (t *apiKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) { req.Header.Set("Authorization", "Token token="+t.APIKey) return http.DefaultTransport.RoundTrip(req) }

Basic API Operations

Now that we've got authentication sorted, let's implement some basic API operations. We'll create functions for GET, POST, PUT, and DELETE requests:

func get(client *http.Client, endpoint string) (*http.Response, error) { return client.Get(baseURL + endpoint) } func post(client *http.Client, endpoint string, body io.Reader) (*http.Response, error) { return client.Post(baseURL+endpoint, "application/json", body) } func put(client *http.Client, endpoint string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest(http.MethodPut, baseURL+endpoint, body) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") return client.Do(req) } func delete(client *http.Client, endpoint string) (*http.Response, error) { req, err := http.NewRequest(http.MethodDelete, baseURL+endpoint, nil) if err != nil { return nil, err } return client.Do(req) }

Handling Responses

Let's create a helper function to handle API responses:

func handleResponse(resp *http.Response) ([]byte, error) { defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("API request failed with status code %d: %s", resp.StatusCode, body) } return body, nil }

Implementing Specific Freshsales Suite Endpoints

Now, let's implement some specific Freshsales Suite endpoints. We'll start with the Contacts API:

type Contact struct { ID int `json:"id"` Email string `json:"email"` // Add other fields as needed } func getContacts(client *http.Client) ([]Contact, error) { resp, err := get(client, "/contacts") if err != nil { return nil, err } body, err := handleResponse(resp) if err != nil { return nil, err } var result struct { Contacts []Contact `json:"contacts"` } if err := json.Unmarshal(body, &result); err != nil { return nil, err } return result.Contacts, nil }

Rate Limiting and Pagination

Freshsales API has rate limits and uses pagination for large datasets. Let's implement a function to handle paginated responses:

func getPaginatedResults(client *http.Client, endpoint string) ([]json.RawMessage, error) { var allResults []json.RawMessage page := 1 for { resp, err := get(client, fmt.Sprintf("%s?page=%d", endpoint, page)) if err != nil { return nil, err } body, err := handleResponse(resp) if err != nil { return nil, err } var pageResults []json.RawMessage if err := json.Unmarshal(body, &pageResults); err != nil { return nil, err } allResults = append(allResults, pageResults...) if len(pageResults) == 0 { break } page++ time.Sleep(time.Second) // Simple rate limiting } return allResults, nil }

Testing

Don't forget to test your integration! Here's a simple example of how you might test the getContacts function:

func TestGetContacts(t *testing.T) { client := newClient("your-api-key") contacts, err := getContacts(client) if err != nil { t.Fatalf("Error getting contacts: %v", err) } if len(contacts) == 0 { t.Fatal("No contacts returned") } // Add more assertions as needed }

Best Practices

As you build out your integration, keep these best practices in mind:

  • Always handle errors gracefully
  • Use logging to track API calls and responses
  • Consider implementing retries for failed requests
  • Keep an eye on API versioning and update your integration as needed

Conclusion

And there you have it! You've now got the building blocks for a solid Freshsales Suite API integration in Go. Remember, this is just the beginning - there's a whole world of Freshsales data out there waiting for you to explore and integrate.

Keep experimenting, keep coding, and most importantly, have fun with it! If you run into any snags, the Freshsales API documentation is your best friend. Happy coding!