> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Importly from a Go backend

> Transcribe or download any video or audio link from a Go server with the standard library: a small client, polling with a context deadline, and a webhook handler that checks the signature.

If your Go service takes video or podcast links, the media step is the one that breaks once it runs on a server: sites block datacenter IPs, and many videos have no captions to read. Call Importly instead. It returns the transcript, a download link for the file, or the video's details, for links from YouTube, TikTok, Instagram, X, podcasts and 1,000+ other sites.

The code below uses only the standard library and Go 1.22 or later. It's one small package, `importly`, plus two HTTP handlers.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once) and put it in your server's environment. The webhook signing secret is on the same page, under **Webhook signing secret**:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
IMPORTLY_WEBHOOK_SECRET=whsec_your_signing_secret
```

## 2. A small client

`Call` returns the job, or an `*APIError` when the API refused the request. A `429` carries the `retryAfter` the API sent. `Final()` is true for a `400` (a bad link), `401` (a wrong key) or `402` (balance too low), which a retry won't change:

```go importly/client.go theme={null}
package importly

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

var (
	BaseURL    = "https://api.importly.io"
	apiKey     = os.Getenv("IMPORTLY_API_KEY")
	httpClient = &http.Client{Timeout: 70 * time.Second} // longer than the 30-second wait on /transcribe
)

// Job is what the start and status endpoints return.
type Job struct {
	JobID   string          `json:"jobId"`
	Status  string          `json:"status"` // queued, running, completed or failed
	Result  json.RawMessage `json:"result,omitempty"`
	Code    string          `json:"code,omitempty"`
	Message string          `json:"message,omitempty"`
}

// APIError is a request the API refused.
type APIError struct {
	Status     int
	Code       string
	Message    string
	RetryAfter time.Duration // set on a 429
}

func (e *APIError) Error() string {
	return fmt.Sprintf("importly %d %s: %s", e.Status, e.Code, e.Message)
}

// Final is true for a bad link (400), a wrong key (401) or a low balance (402): a retry won't change it.
func (e *APIError) Final() bool {
	return e.Status == 400 || e.Status == 401 || e.Status == 402
}

func Call(ctx context.Context, method, path string, body any) (*Job, error) {
	var reader io.Reader
	if body != nil {
		b, err := json.Marshal(body)
		if err != nil {
			return nil, err
		}
		reader = bytes.NewReader(b)
	}
	req, err := http.NewRequestWithContext(ctx, method, BaseURL+path, reader)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	var out struct {
		Success    bool   `json:"success"`
		Data       *Job   `json:"data"`
		Error      string `json:"error"`
		Code       string `json:"code"`
		RetryAfter int    `json:"retryAfter"`
	}
	if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
		return nil, fmt.Errorf("importly %d: %w", res.StatusCode, err)
	}
	if res.StatusCode < 300 && out.Success && out.Data != nil {
		return out.Data, nil
	}
	apiErr := &APIError{Status: res.StatusCode, Code: out.Code, Message: out.Error}
	if res.StatusCode == http.StatusTooManyRequests {
		apiErr.RetryAfter = time.Duration(max(out.RetryAfter, 1)) * time.Second
	}
	return nil, apiErr
}
```

## 3. Transcripts and downloads

`"mode": "auto"` uses the video's captions and falls back to speech-to-text when it has none. `wait: true` holds the request open for up to 30 seconds, so a transcript from captions usually comes back from the first call. `POST /import` returns a job ID straight away. `WaitFor` checks a job until it's done, waits for `retryAfter` on a `429`, and stops when the context ends:

```go importly/jobs.go theme={null}
package importly

import (
	"context"
	"errors"
	"fmt"
	"net/url"
	"time"
)

// Transcribe starts a transcript. Captions usually come back within the 30-second wait.
func Transcribe(ctx context.Context, link string) (*Job, error) {
	return Call(ctx, "POST", "/transcribe", map[string]any{
		"url":            link,
		"mode":           "auto", // captions, or speech-to-text when there are none
		"wait":           true,
		"maxCostDollars": 1,
	})
}

// Import starts a download and returns the job straight away.
func Import(ctx context.Context, link string, audioOnly bool) (*Job, error) {
	return Call(ctx, "POST", "/import", map[string]any{
		"url":            link,
		"includeVideo":   !audioOnly,
		"videoQuality":   "720p", // a ceiling: lower if the source has no 720p
		"maxCostDollars": 0.5,    // the most this one file may cost
	})
}

// Status reads a job. kind is "transcribe" or "import".
func Status(ctx context.Context, kind, jobID string) (*Job, error) {
	return Call(ctx, "GET", fmt.Sprintf("/%s/status?id=%s", kind, url.QueryEscape(jobID)), nil)
}

// PollEvery is how often WaitFor checks a job.
var PollEvery = 20 * time.Second

// WaitFor checks the job every PollEvery until it finishes or ctx ends.
func WaitFor(ctx context.Context, kind string, job *Job) (*Job, error) {
	for job.Status == "queued" || job.Status == "running" {
		delay := PollEvery
		next, err := Status(ctx, kind, job.JobID)
		var apiErr *APIError
		switch {
		case errors.As(err, &apiErr) && apiErr.RetryAfter > 0:
			delay = apiErr.RetryAfter
		case err != nil:
			return job, err
		default:
			job = next
			if job.Status != "queued" && job.Status != "running" {
				return job, nil
			}
		}
		select {
		case <-ctx.Done():
			return job, ctx.Err()
		case <-time.After(delay):
		}
	}
	return job, nil
}
```

Run long jobs outside the request, in a goroutine or your job queue, with a deadline:

```go theme={null}
ctx, cancel := context.WithTimeout(context.Background(), time.Hour)
defer cancel()

job, err := importly.Import(ctx, link, false)
if err == nil {
	job, err = importly.WaitFor(ctx, "import", job)
}
// job.Status is "completed" (job.Result has mediaUrl) or "failed" (job.Code, job.Message)
```

A finished transcript's `result` has `text`, and `data.segments` with `start` and `end` times in seconds. A finished import's `result` has `mediaUrl`, a link to the file that's valid for 7 days: copy the file to your storage if you keep it, or connect your bucket once and import with `"store": true` ([Save to your bucket](/docs/integrations/save-to-bucket.md)). A caption transcript costs \$0.003; speech-to-text is billed per minute, and `maxCostDollars` caps what one link can cost. See [Transcripts](/docs/features/transcripts.md) and [Downloads](/docs/features/downloads.md).

## 4. Webhooks in production

When a job belongs to a record in your database, add `"webhookUrl": "https://your-app.example/webhooks/importly"` to the start request and store the `jobId` with the record. Importly sends one `POST` when the job finishes. Check its signature on the raw body first (see [Verify signatures](/docs/webhooks.md#verify-signatures)):

```go importly/webhook.go theme={null}
package importly

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"math"
	"strconv"
	"strings"
	"time"
)

// VerifySignature checks the Importly-Signature header against the raw request body.
func VerifySignature(header string, rawBody []byte, secret string) bool {
	var timestamp int64 = -1
	var signatures []string
	for _, part := range strings.Split(header, ",") {
		key, value, _ := strings.Cut(strings.TrimSpace(part), "=")
		switch key {
		case "t":
			if t, err := strconv.ParseInt(value, 10, 64); err == nil {
				timestamp = t
			}
		case "v1":
			signatures = append(signatures, value)
		}
	}
	// Reject requests older (or newer) than 5 minutes, so a captured one can't be replayed
	if timestamp < 0 || math.Abs(float64(time.Now().Unix()-timestamp)) > 300 {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret)) // the whole secret, whsec_ included
	mac.Write([]byte(strconv.FormatInt(timestamp, 10) + "."))
	mac.Write(rawBody)
	expected := hex.EncodeToString(mac.Sum(nil))
	for _, signature := range signatures {
		if hmac.Equal([]byte(signature), []byte(expected)) {
			return true
		}
	}
	return false
}
```

The handlers below start a transcript from a form post and take the webhook. The webhook handler only takes the `jobId` from the body and reads the job from the API with your key, so even a request that got past the signature check can't put data into your app:

```go main.go theme={null}
package main

import (
	"encoding/json"
	"errors"
	"io"
	"log"
	"net/http"
	"os"

	"example.com/myapp/importly"
)

func transcribeHandler(w http.ResponseWriter, r *http.Request) {
	job, err := importly.Transcribe(r.Context(), r.FormValue("url"))
	var apiErr *importly.APIError
	if errors.As(err, &apiErr) && apiErr.Final() {
		http.Error(w, apiErr.Message, apiErr.Status) // show the user what's wrong with the link
		return
	}
	if err != nil {
		http.Error(w, "try again in a minute", http.StatusServiceUnavailable)
		return
	}
	// "completed" with result.text, "failed" with code and message,
	// or "queued"/"running": store job.JobID and check later with importly.Status
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(job)
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
	raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil || !importly.VerifySignature(r.Header.Get("Importly-Signature"), raw, os.Getenv("IMPORTLY_WEBHOOK_SECRET")) {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	var payload struct {
		Data struct {
			JobID string `json:"jobId"`
			Type  string `json:"type"`
		} `json:"data"`
	}
	if json.Unmarshal(raw, &payload) != nil || (payload.Data.Type != "import" && payload.Data.Type != "transcribe") {
		w.WriteHeader(http.StatusOK)
		return
	}
	// Read the job from the API with your key instead of trusting the body
	job, err := importly.Status(r.Context(), payload.Data.Type, payload.Data.JobID)
	if err != nil {
		w.WriteHeader(http.StatusOK) // the pending-job check below picks it up
		return
	}
	saveResult(job) // find your record by job.JobID; skip it if it's already saved
	w.WriteHeader(http.StatusOK)
}

func saveResult(job *importly.Job) {
	log.Printf("job %s %s", job.JobID, job.Status) // write job.Result, or job.Code and job.Message, to your database
}

func main() {
	http.HandleFunc("POST /transcribe", transcribeHandler)
	http.HandleFunc("POST /webhooks/importly", webhookHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

Each job gets one delivery and no retries, so also check jobs that have been pending for a few minutes with `importly.Status`. The webhook URL must be public `https://`, so a server on `localhost` gets nothing: use `WaitFor` in development. See [Webhooks](/docs/webhooks.md).

## Notes

`SOURCE_THROTTLED` and `LIVE_NOT_SUPPORTED` are the failure codes that can work on a later attempt (a stream that is still live, or a site that is busy for now). Start a new job for those later; every other failure code is final. See [Media unavailable](/docs/errors/media-unavailable.md) and [Source throttled](/docs/errors/source-throttled.md).

`POST /import` allows 240 requests per hour per key, and an account can have 50 imports queued or running at once. Status endpoints allow 3,600 requests per hour per job type; a check every 20 seconds is 180 an hour for each job in progress, so about 20 jobs can poll at once. For hundreds of links, see [Batch imports](/docs/integrations/batch-imports.md).

A `youtube.com/playlist?list=…` link is rejected with `PLAYLIST_NOT_SUPPORTED`. Send one request per video instead.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.