Hey there, fellow developer! Ready to dive into the world of SafetyCulture 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 pulling inspection data like a pro in no time.
Before we jump in, make sure you've got:
Let's kick things off by creating a new Go module:
mkdir safety-culture-integration && cd safety-culture-integration go mod init github.com/yourusername/safety-culture-integration
Now, let's grab the HTTP client we'll be using:
go get -u github.com/go-resty/resty/v2
First things first, we need to authenticate. SafetyCulture uses token-based auth, so let's set that up:
import "github.com/go-resty/resty/v2" client := resty.New() client.SetHeader("Authorization", "Bearer YOUR_API_TOKEN")
Now that we're authenticated, let's create a function to make API calls:
func makeAPICall(endpoint string) (*resty.Response, error) { return client.R().Get("https://api.safetyculture.io/audits/v1/" + endpoint) }
Let's implement some core functionality:
func fetchInspections() (*resty.Response, error) { return makeAPICall("audits") } func getInspectionDetails(inspectionID string) (*resty.Response, error) { return makeAPICall("audits/" + inspectionID) } func downloadInspectionReport(inspectionID string) (*resty.Response, error) { return makeAPICall("audits/" + inspectionID + "/report") }
Always check for errors and respect rate limits:
resp, err := fetchInspections() if err != nil { log.Fatalf("API call failed: %v", err) } if resp.StatusCode() == 429 { // Handle rate limiting time.Sleep(time.Second * 5) // Retry the request }
Parse those JSON responses like a champ:
var inspections []Inspection err := json.Unmarshal(resp.Body(), &inspections) if err != nil { log.Fatalf("Failed to parse JSON: %v", err) } // Store or process inspections as needed
Let's wrap this all up in a neat CLI package:
package main import ( "flag" "fmt" "log" ) func main() { action := flag.String("action", "list", "Action to perform: list, details, report") id := flag.String("id", "", "Inspection ID for details or report") flag.Parse() switch *action { case "list": // Fetch and display inspections case "details": // Get and display inspection details case "report": // Download inspection report default: log.Fatalf("Unknown action: %s", *action) } }
Don't forget to test! Here's a simple example:
func TestFetchInspections(t *testing.T) { resp, err := fetchInspections() if err != nil { t.Fatalf("Failed to fetch inspections: %v", err) } if resp.StatusCode() != 200 { t.Fatalf("Expected status code 200, got %d", resp.StatusCode()) } }
Remember to:
And there you have it! You've just built a solid SafetyCulture API integration in Go. Pretty cool, right? Remember, this is just the beginning. There's a whole world of possibilities with the SafetyCulture API, so don't be afraid to explore and expand on what we've built here.
For more info, check out the SafetyCulture API docs. Now go forth and integrate!