Tutorial · Go

Instagram and TikTok API in Go

A standard-library Go client with generic Page[T] and One[T] types: decode the fields you need into structs, page with a callback, and get a typed APIError for anything else.

Short answer. http.NewRequest with X-Api-Key, decode { data, pagination, meta } into a struct, and loop on pagination.next_cursor. The client below adds retries and generics (Go 1.18+). The endpoint pages use maps instead, so they run without defining types.

Facts checked 2 December 2026. Prices change: follow the links before you decide.

Set up

  • Go 1.18 or newer (generics). No modules beyond the standard library. Read the key from HANDLEHAUL_API_KEY with os.Getenv or your config loader.
  • Ids are strings in the JSON (they can exceed 2^53): keep them as string in your structs. Counts fit in int64. Fields the API may send as null (like TikTok counts.views on some posts) decode to zero unless you use pointers.

The typed client

  • Client.Get() retries 429 after Retry-After and 502/503/504 with a growing wait plus jitter, and adds meta.credits_charged to Client.Credits.
  • Paginate[T]() calls your function for every row, up to maxPages pages (one call each). Errors come back as *APIError with Status and Code, so errors.As or a type switch can tell private_account from insufficient_credits.
  • Run several calls at once with a buffered channel or errgroup with a small limit; your account's speed limit is shared by all its keys.

handlehaul.goRun: go run handlehaul.go

// A small HandleHaul API client for Go (standard library only): typed responses, retries,
// cursor paging and clear errors.
//
//	export HANDLEHAUL_API_KEY=kd_live_...   # or a free kd_test_ key for sample data
//	go run handlehaul.go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"time"
)

const api = "https://api.handlehaul.com/v1"

// Meta comes with every answer.
type Meta struct {
	CreditsCharged float64 `json:"credits_charged"`
	Cached         bool    `json:"cached"`
}

// Pagination comes with every list.
type Pagination struct {
	NextCursor *string `json:"next_cursor"`
	HasMore    bool    `json:"has_more"`
}

// Page is one page of a list endpoint; T is the row type.
type Page[T any] struct {
	Data       []T        `json:"data"`
	Pagination Pagination `json:"pagination"`
	Meta       Meta       `json:"meta"`
}

// One is a single-object answer.
type One[T any] struct {
	Data T    `json:"data"`
	Meta Meta `json:"meta"`
}

// Profile holds the Instagram profile fields this program uses (add the ones you need).
type Profile struct {
	ID       string `json:"id"` // a string: ids can exceed 2^53
	Username string `json:"username"`
	Counts   struct {
		Followers int64 `json:"followers"`
		Posts     int64 `json:"posts"`
	} `json:"counts"`
}

// FollowItem is one row of a followers or following page.
type FollowItem struct {
	Position int    `json:"position"`
	Username string `json:"username"`
}

// APIError is any non-2xx answer.
type APIError struct {
	Status  int
	Code    string `json:"code"`
	Message string `json:"message"`
}

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

// Client calls the API. Credits adds up meta.credits_charged.
type Client struct {
	Key     string
	HTTP    *http.Client
	Credits float64
}

func NewClient() *Client {
	return &Client{Key: os.Getenv("HANDLEHAUL_API_KEY"), HTTP: &http.Client{Timeout: 60 * time.Second}}
}

// Get calls one endpoint and decodes the answer into out. 429 waits for Retry-After;
// 502, 503 and 504 wait 1, 2, 4... seconds. Those answers are never charged.
func (c *Client) Get(path string, params url.Values, out any) error {
	u := api + path
	if len(params) > 0 {
		u += "?" + params.Encode()
	}
	for attempt := 0; attempt < 5; attempt++ {
		req, err := http.NewRequest(http.MethodGet, u, nil)
		if err != nil {
			return err
		}
		req.Header.Set("X-Api-Key", c.Key)
		res, err := c.HTTP.Do(req)
		if err != nil {
			return err
		}
		raw, err := io.ReadAll(res.Body)
		res.Body.Close()
		if err != nil {
			return err
		}
		switch res.StatusCode {
		case 429, 502, 503, 504:
			if attempt < 4 {
				wait, _ := strconv.ParseFloat(res.Header.Get("Retry-After"), 64)
				if wait <= 0 {
					wait = float64(int(1)<<attempt) + rand.Float64()
				}
				time.Sleep(time.Duration(wait * float64(time.Second)))
				continue
			}
		}
		if res.StatusCode >= 400 {
			var body struct {
				Error APIError `json:"error"`
			}
			_ = json.Unmarshal(raw, &body)
			body.Error.Status = res.StatusCode
			return &body.Error
		}
		var m struct {
			Meta Meta `json:"meta"`
		}
		_ = json.Unmarshal(raw, &m)
		c.Credits += m.Meta.CreditsCharged
		return json.Unmarshal(raw, out)
	}
	return &APIError{Status: 429, Code: "rate_limited", Message: "still limited after retries"}
}

// Paginate calls fn for every row of a list endpoint, at most maxPages pages (one call each).
func Paginate[T any](c *Client, path string, params url.Values, maxPages int, fn func(T)) error {
	if params == nil {
		params = url.Values{}
	}
	for page := 0; page < maxPages; page++ {
		var p Page[T]
		if err := c.Get(path, params, &p); err != nil {
			return err
		}
		for _, row := range p.Data {
			fn(row)
		}
		if !p.Pagination.HasMore || p.Pagination.NextCursor == nil {
			return nil
		}
		params.Set("cursor", *p.Pagination.NextCursor)
	}
	return nil
}

func main() {
	c := NewClient()
	var profile One[Profile]
	if err := c.Get("/instagram/users/natgeo", nil, &profile); err != nil {
		log.Fatal(err)
	}
	fmt.Println(profile.Data.Username, profile.Data.Counts.Followers, "followers")

	err := Paginate(c, "/instagram/users/"+profile.Data.ID+"/followers", nil, 2, func(f FollowItem) {
		fmt.Println(f.Position, f.Username)
	})
	if err != nil {
		log.Fatal(err)
	}

	var p Page[FollowItem]
	if err := c.Get("/instagram/users/private_demo/followers", nil, &p); err != nil {
		if apiErr, ok := err.(*APIError); ok {
			fmt.Println("expected error:", apiErr.Code)
		}
	}
	fmt.Println("credits used:", c.Credits)
}
Tested 2026-12-02 against a local mock serving the documented API responses (retry on 429, cursor paging, a private-account error).

Every endpoint in Go

Each page below has a complete Go program for one route, the parameters, a sample response and what it costs. The link opens the Go tab.

Instagram

Instagram endpoint tutorials
TutorialRoute
ProfileGET /v1/instagram/users/{user}
Account detailsGET /v1/instagram/users/{user}/account-details
Similar accountsGET /v1/instagram/users/{user}/related
FollowersGET /v1/instagram/users/{user}/followers
FollowingGET /v1/instagram/users/{user}/following
PostsGET /v1/instagram/users/{user}/posts
ReelsGET /v1/instagram/users/{user}/reels
Tagged postsGET /v1/instagram/users/{user}/tagged
RepostsGET /v1/instagram/users/{user}/reposts
Post or reelGET /v1/instagram/posts/{post}
Post stats (batch)GET /v1/instagram/posts/stats
CommentsGET /v1/instagram/posts/{post}/comments
Comment repliesGET /v1/instagram/comments/{comment}/replies
Post likersGET /v1/instagram/posts/{post}/likers
Comment likersGET /v1/instagram/comments/{comment}/likers
StoriesGET /v1/instagram/users/{user}/stories
Story by idGET /v1/instagram/stories/{story}
HighlightsGET /v1/instagram/users/{user}/highlights
Highlight storiesGET /v1/instagram/highlights/{highlight}
Search hashtagsGET /v1/instagram/search/hashtags
HashtagGET /v1/instagram/hashtags/{tag}
Hashtag postsGET /v1/instagram/hashtags/{tag}/posts
Search placesGET /v1/instagram/search/places
PlaceGET /v1/instagram/places/{place}
Place postsGET /v1/instagram/places/{place}/posts
Search audioGET /v1/instagram/search/audio
Trending audioGET /v1/instagram/audio/trending
AudioGET /v1/instagram/audio/{audio}
Reels using audioGET /v1/instagram/audio/{audio}/reels
Search accountsGET /v1/instagram/search/users
URL resolverGET /v1/instagram/resolve

TikTok

TikTok endpoint tutorials
TutorialRoute
ProfileGET /v1/tiktok/users/{user}
Suggested accountsGET /v1/tiktok/users/{user}/suggested
FollowersGET /v1/tiktok/users/{user}/followers
FollowingGET /v1/tiktok/users/{user}/following
PostsGET /v1/tiktok/users/{user}/posts
RepostsGET /v1/tiktok/users/{user}/reposts
Liked videosGET /v1/tiktok/users/{user}/liked
PlaylistsGET /v1/tiktok/users/{user}/playlists
StoriesGET /v1/tiktok/users/{user}/stories
Video or photo postGET /v1/tiktok/posts/{post}
CommentsGET /v1/tiktok/posts/{post}/comments
Comment repliesGET /v1/tiktok/comments/{comment}/replies
TranscriptGET /v1/tiktok/posts/{post}/transcript
SoundGET /v1/tiktok/music/{music}
Posts using a soundGET /v1/tiktok/music/{music}/posts
HashtagGET /v1/tiktok/hashtags/{tag}
Hashtag postsGET /v1/tiktok/hashtags/{tag}/posts
SearchGET /v1/tiktok/search

Go: questions

Is there a Go SDK for HandleHaul?
Not yet: the official SDKs are Node.js and Python. The OpenAPI spec at api.handlehaul.com/openapi.json works with Go generators such as oapi-codegen if you want generated types; the client above is enough for most jobs.
Why does my Go program print big ids in scientific notation?
Decoding JSON numbers into interface{} gives float64. Use typed structs, or json.Decoder.UseNumber() as the endpoint samples do, and keep ids as strings.
How do I stop paging early in Go?
Set maxPages, or have your callback record that you have enough and return early from the loop. Each page is one billed call, and the newest rows are on page one for newest-first lists.

Build it in Go

One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls and cache hits are free.

Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.