Back

Step by Step Guide to Building a Formstack Documents API Integration in Go

Aug 16, 20247 minute read

Introduction

Hey there, fellow Go enthusiast! Ready to supercharge your document automation game? Let's dive into building a Formstack Documents API integration in Go. This powerful combo will let you generate documents on the fly, merge data like a pro, and streamline your workflow. Buckle up!

Prerequisites

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

  • Go installed (you're a Gopher, right?)
  • A Formstack Documents account with an API key
  • Your favorite code editor

Setting up the project

Let's get this party started:

mkdir formstack-docs-integration cd formstack-docs-integration go mod init formstack-docs-integration

Now, let's grab the HTTP client we'll need:

go get github.com/go-resty/resty/v2

Authentication

Formstack uses API key authentication. Let's set that up:

package main import ( "github.com/go-resty/resty/v2" ) const ( baseURL = "https://www.webmerge.me/api/v1" apiKey = "your-api-key-here" ) func main() { client := resty.New(). SetBaseURL(baseURL). SetHeader("Authorization", "Basic "+apiKey) // We'll use this client for all our requests }

Basic API Operations

Fetching document templates

Let's grab those templates:

resp, err := client.R(). SetResult([]map[string]interface{}{}). Get("/documents") if err != nil { log.Fatalf("Error fetching templates: %v", err) } templates := resp.Result().(*[]map[string]interface{}) fmt.Printf("Found %d templates\n", len(*templates))

Creating a new document

Time to make some magic happen:

payload := map[string]interface{}{ "name": "Awesome Contract", "type": "pdf", } resp, err := client.R(). SetBody(payload). SetResult(map[string]interface{}{}). Post("/documents") if err != nil { log.Fatalf("Error creating document: %v", err) } newDoc := resp.Result().(*map[string]interface{}) fmt.Printf("Created document with ID: %v\n", (*newDoc)["id"])

Retrieving document status

Let's check on our document:

docID := "123" // Use the ID from the previous step resp, err := client.R(). SetResult(map[string]interface{}{}). Get("/documents/" + docID) if err != nil { log.Fatalf("Error fetching document: %v", err) } docStatus := resp.Result().(*map[string]interface{}) fmt.Printf("Document status: %v\n", (*docStatus)["status"])

Advanced Features

Merging data into templates

Now for the real magic - let's merge some data:

docID := "123" mergeData := map[string]interface{}{ "name": "John Doe", "company": "Awesome Inc.", } resp, err := client.R(). SetBody(mergeData). SetResult(map[string]interface{}{}). Post("/documents/" + docID + "/merge") if err != nil { log.Fatalf("Error merging data: %v", err) } mergeResult := resp.Result().(*map[string]interface{}) fmt.Printf("Merge job ID: %v\n", (*mergeResult)["job_id"])

Handling callbacks

Formstack can notify you when a job's done. Set up an endpoint to handle that:

http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) { var data map[string]interface{} json.NewDecoder(r.Body).Decode(&data) fmt.Printf("Received callback for job: %v\n", data["job_id"]) // Process the completed job here })

Error handling and retries

Let's add some resilience:

client.SetRetryCount(3). SetRetryWaitTime(5 * time.Second). AddRetryCondition(func(r *resty.Response, err error) bool { return r.StatusCode() >= 500 })

Testing the Integration

Don't forget to test! Here's a quick unit test example:

func TestCreateDocument(t *testing.T) { // Mock the API response // Test document creation // Assert the results }

Best Practices

  • Respect rate limits (Formstack will let you know the limits in response headers)
  • Log API calls and responses for debugging
  • Keep your API key secret and use environment variables

Conclusion

And there you have it! You've just built a robust Formstack Documents API integration in Go. You're now ready to automate document creation like a boss. Remember, practice makes perfect, so keep experimenting and building awesome stuff!

Sample Code

Here's a complete working example to get you started:

package main import ( "fmt" "log" "os" "github.com/go-resty/resty/v2" ) func main() { client := resty.New(). SetBaseURL("https://www.webmerge.me/api/v1"). SetHeader("Authorization", "Basic "+os.Getenv("FORMSTACK_API_KEY")) // Fetch templates resp, err := client.R(). SetResult([]map[string]interface{}{}). Get("/documents") if err != nil { log.Fatalf("Error fetching templates: %v", err) } templates := resp.Result().(*[]map[string]interface{}) fmt.Printf("Found %d templates\n", len(*templates)) // Create a new document payload := map[string]interface{}{ "name": "Awesome Contract", "type": "pdf", } resp, err = client.R(). SetBody(payload). SetResult(map[string]interface{}{}). Post("/documents") if err != nil { log.Fatalf("Error creating document: %v", err) } newDoc := resp.Result().(*map[string]interface{}) fmt.Printf("Created document with ID: %v\n", (*newDoc)["id"]) // The rest of your integration code goes here... }

Now go forth and automate those documents! Happy coding!