Instagram API Go Client
Features
- π Type-safe API clients generated from OpenAPI/Swagger specifications
- π Media Insights: Fetch insights for individual Instagram posts (reach, likes, comments, etc.)
- π₯ Account Insights: Fetch account-level metrics (engagement, demographics, etc.)
- π Built-in authentication via access token
- π― Support for different metric periods and breakdowns
- π οΈ Unified singleton client pattern with thread-safe initialization
- π¦ Shared configuration for both API clients
Installation
go get github.com/qcserestipy/instagram-api-go-client
Prerequisites
- Go 1.25.0 or higher
- Instagram Business Account
- Facebook Graph API access token with appropriate permissions
Configuration
Set your Facebook Graph API access token as an environment variable:
export ACCESS_TOKEN="your-access-token-here"
Usage
Get insights for a specific Instagram post:
package main
import (
"context"
"fmt"
"github.com/qcserestipy/instagram-api-go-client/pkg/client"
"github.com/qcserestipy/instagram-api-go-client/pkg/media"
"github.com/qcserestipy/instagram-api-go-client/pkg/sdk/v24.0/media/client/insights"
"github.com/sirupsen/logrus"
)
func main() {
ctx := context.Background()
// Create the Instagram client
igClient, err := client.NewDefault()
if err != nil {
logrus.Fatalf("error creating client: %v", err)
}
// Create parameters for media insights
params := insights.NewGetInsightsByMediaIDParams()
params.InstagramMediaID = "123456789101112"
params.Metric = "reach,likes,comments"
params.Period = "day"
// Create media service and fetch insights
svc := media.NewService(igClient)
resp, err := svc.GetInsightsByMediaID(ctx, params)
if err != nil {
logrus.Fatalf("error: %v", err)
}
// Process the response
if resp.Payload != nil && resp.Payload.Data != nil {
for _, data := range resp.Payload.Data {
fmt.Printf("Metric: %s, Title: %s\n", data.Name, data.Title)
if data.Values != nil {
for _, val := range data.Values {
fmt.Printf(" Value: %d\n", val.Value)
}
}
}
}
}
Account Insights Example
Get account-level insights with demographic breakdowns:
package main
import (
"context"
"fmt"
"github.com/qcserestipy/instagram-api-go-client/pkg/account"
"github.com/qcserestipy/instagram-api-go-client/pkg/client"
accinsights "github.com/qcserestipy/instagram-api-go-client/pkg/sdk/v24.0/account/client/insights"
"github.com/sirupsen/logrus"
)
func main() {
ctx := context.Background()
// Create the Instagram client
igClient, err := client.NewDefault()
if err != nil {
logrus.Fatalf("error creating client: %v", err)
}
// Create parameters for account insights
params := accinsights.NewGetInsightsByAccountIDParams()
params.InstagramAccountID = "123456789101112"
params.Metric = "engaged_audience_demographics"
params.Period = "lifetime"
metricType := "total_value"
params.MetricType = &metricType
timeframe := "this_month"
params.Timeframe = &timeframe
breakdown := "country"
params.Breakdown = &breakdown
// Create account service and fetch insights
svc := account.NewService(igClient)
resp, err := svc.GetInsightsByAccountID(ctx, params)
if err != nil {
logrus.Fatalf("error: %v", err)
}
// Process demographic breakdowns
if resp.Payload != nil && resp.Payload.Data != nil {
for _, data := range resp.Payload.Data {
fmt.Printf("Metric: %s\n", data.Name)
if data.TotalValue != nil && data.TotalValue.Breakdowns != nil {
for _, breakdown := range data.TotalValue.Breakdowns {
for _, result := range breakdown.Results {
fmt.Printf(" %s: %d\n", result.DimensionValues[0], result.Value)
}
}
}
}
}
}
Available Metrics
reach - Total number of unique accounts that have seen the media
likes - Number of likes
comments - Number of comments
saved - Number of times the media was saved
engagement - Total engagement (likes + comments + saves)
impressions - Total number of times the media was seen
Account Insights Metrics
Interaction Metrics (period: day):
accounts_engaged - Number of accounts that interacted with content
reach - Number of unique accounts that saw content
likes - Total likes on posts, reels, and videos
comments - Total comments
shares - Total shares
saved - Total saves
total_interactions - Sum of all interactions
views - Total views of content
Demographic Metrics (period: lifetime):
engaged_audience_demographics - Demographics of engaged users
follower_demographics - Demographics of followers
Available breakdowns: age, city, country, gender, media_product_type, follow_type
Period Options
day - Daily metrics (for interaction metrics)
lifetime - Lifetime metrics (for demographic metrics)
Metric Types
total_value - Simple total with optional breakdowns
time_series - Aggregated by time period
Project Structure
.
βββ cmd/
β βββ main/
β βββ main.go # Example application
βββ pkg/
β βββ access/
β β βββ service.go # Authentication service
β β βββ token_handler.go # Token handling
β βββ account/
β β βββ service.go # Account service
β β βββ insights_handler.go # Account insights operations
β β βββ media_handler.go # Account media operations
β β βββ stories_handler.go # Account stories operations
β β βββ user_handler.go # Account user operations
β βββ client/
β β βββ client.go # Unified client for all APIs
β βββ config/
β β βββ config.go # Shared configuration
β βββ instagram/
β β βββ account-info.go # Account info types
β β βββ demographics.go # Demographics data
β β βββ followers.go # Followers data
β β βββ reels.go # Reels data
β β βββ stories.go # Stories data
β β βββ types.go # Common types
β βββ media/
β β βββ service.go # Media service
β β βββ comments_handler.go # Media comments operations
β β βββ insights_handler.go # Media insights operations
β β βββ media_handler.go # Media operations
β βββ sdk/
β βββ v24.0/
β βββ media/
β β βββ client/ # Generated media API client
β β βββ models/ # Generated media data models
β βββ account/
β β βββ client/ # Generated account API client
β β βββ models/ # Generated account data models
β βββ page/
β βββ client/ # Generated page API client
β βββ models/ # Generated page data models
βββ api/ # Git submodule with Swagger specs
β βββ v24.0/
βββ bin/
β βββ instagram-media-insights-go-client # Compiled binary
βββ Makefile # Build automation
βββ CONTRIBUTE.md # Contribution guidelines
βββ go.mod
βββ go.sum
βββ README.md
Building
# Build the example application
go build -o ./bin/main cmd/main/main.go
# Or use make
make build
# Run the example
./bin/main
Makefile Commands
# Generate media insights client
make gen-api-client
# Generate account insights client
make gen-api-client-account
# Generate both clients
make gen-all-clients
# Clean generated code
make cleanup
# Build the application
make build
# Run tests
make test
# Update git submodule with latest specs
make update-submodule
# Clean and regenerate everything
make all
API Reference
Unified Client
client.NewDefault() (*InstagramClient, error)
Creates a new Instagram client using environment configuration (requires ACCESS_TOKEN env var).
Returns: (*InstagramClient, error)
The InstagramClient struct provides:
Media - Instagram Media Insights API client
Account - Instagram Account Insights API client
Page - Facebook Page API client
client.NewFromConfig(apiURL *url.URL, authInfo runtime.ClientAuthInfoWriter) (*InstagramClient, error)
Creates a new Instagram client with custom configuration.
Parameters:
apiURL - Base URL for the API
authInfo - Authentication info writer
Returns: (*InstagramClient, error)
Creates a new media insights service.
service.GetInsightsByMediaID(ctx context.Context, params *insights.GetInsightsByMediaIDParams) (*insights.GetInsightsByMediaIDOK, error)
Fetches insights for a specific Instagram media by its ID.
Parameters:
params.InstagramMediaID (string, required) - The Instagram media ID
params.Metric (string, required) - Comma-separated list of metrics
params.Period (string, required) - Time period for metrics (day, week, days_28, lifetime)
params.Breakdown (*string, optional) - Breakdown dimension
params.MetricType (*string, optional) - Metric aggregation type
Returns: (*insights.GetInsightsByMediaIDOK, error)
Account Insights Service
account.NewService(c *InstagramClient) *Service
Creates a new account insights service.
service.GetInsightsByAccountID(ctx context.Context, params *insights.GetInsightsByAccountIDParams) (*insights.GetInsightsByAccountIDOK, error)
Fetches insights for an Instagram account.
Parameters:
params.InstagramAccountID (string, required) - The Instagram account ID
params.Metric (string, required) - Comma-separated list of metrics
params.Period (string, required) - Time period (day or lifetime)
params.MetricType (*string, optional) - total_value or time_series
params.Breakdown (*string, optional) - Breakdown dimension
params.Timeframe (*string, optional) - Required for demographics: this_month, this_week
params.Since (*int64, optional) - Unix timestamp for start of range
params.Until (*int64, optional) - Unix timestamp for end of range
Returns: (*insights.GetInsightsByAccountIDOK, error)
Development
The API clients are generated from OpenAPI/Swagger specifications maintained in a separate repository and included as a git submodule.
Updating the API Specifications
# Update the submodule to the latest version
make update-submodule
# Or manually
cd api && git pull origin main && cd ..
# Regenerate both clients
make all
Code Generation
The project uses go-swagger to generate API clients from OpenAPI specifications:
# Generate only media insights client
make gen-api-client
# Generate only account insights client
make gen-api-client-account
# Generate both
make gen-all-clients
Dependencies
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. See CONTRIBUTE.md for guidelines.
License
This project is licensed under the LGPL-3.0 license Β© 2025 Patrick Eschenbach.
Support
For issues and questions:
Made with β€οΈ for the Instagram developer community