instagram-api-go-client

module
v0.0.0-...-37086db Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 7, 2025 License: LGPL-3.0

README ΒΆ

Instagram API Go Client

CI CodeQL Go Reference Go Report Card License

A Go client library for accessing Instagram Media and Account Insights via the Facebook Graph API v24.0. This client is generated from OpenAPI/Swagger specifications and provides type-safe access to Instagram metrics.

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

Media Insights Example

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
Media Insights 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)

Media Insights Service
media.NewService(c *InstagramClient) *Service

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL