Python tutorial · October 2026

Calculate Instagram Engagement Rate with Python

The formula is straightforward. Getting reliable data to plug into it is the hard part. This script solves both.

· 7 minute read

Instagram engagement rate is the metric brands and creators actually care about — it tells you how actively an audience interacts with content, which matters more than raw follower count.

The Formula

The most common engagement rate formula:

Formula
Engagement Rate = (Likes + Comments) / Followers × 100

Some analysts include saves and shares. Others average across multiple posts. This script calculates it both ways — per-post and averaged across recent posts.

The Full Script

This script fetches a public Instagram profile and its recent posts via the GramScraper API, then calculates engagement metrics. You need Python 3.7+ and the requests library.

Python — engagement.py
import requests
import sys

API_BASE = "https://gramscraper.com/api/instagram/v1"
API_KEY = "YOUR_API_KEY"  # Get free 100 credits at gramscraper.com

headers = {"x-api-key": API_KEY}


def get_profile(username):
    """Fetch public profile data."""
    r = requests.get(
        f"{API_BASE}/user/by/username",
        params={"username": username},
        headers=headers,
    )
    r.raise_for_status()
    return r.json()


def get_recent_posts(user_id, count=12):
    """Fetch recent posts for engagement calculation."""
    r = requests.get(
        f"{API_BASE}/user/posts",
        params={"user_id": user_id, "count": count},
        headers=headers,
    )
    r.raise_for_status()
    return r.json()


def calculate_engagement(profile_data, posts_data):
    """Calculate engagement metrics."""
    followers = profile_data.get("follower_count", 0)
    if followers == 0:
        return None

    posts = posts_data.get("items", [])
    if not posts:
        return None

    total_likes = 0
    total_comments = 0
    post_rates = []

    for post in posts:
        likes = post.get("like_count", 0)
        comments = post.get("comment_count", 0)
        total_likes += likes
        total_comments += comments

        post_rate = (likes + comments) / followers * 100
        post_rates.append({
            "shortcode": post.get("code", "?"),
            "likes": likes,
            "comments": comments,
            "engagement_rate": round(post_rate, 3),
        })

    avg_engagement = sum(p["engagement_rate"] for p in post_rates) / len(post_rates)

    return {
        "username": profile_data.get("username"),
        "followers": followers,
        "posts_analyzed": len(posts),
        "total_likes": total_likes,
        "total_comments": total_comments,
        "avg_engagement_rate": round(avg_engagement, 3),
        "per_post": sorted(
            post_rates, key=lambda x: x["engagement_rate"], reverse=True
        ),
    }


def main():
    username = sys.argv[1] if len(sys.argv) > 1 else "instagram"

    print(f"Fetching profile: @{username}")
    profile = get_profile(username)

    user_id = profile.get("pk") or profile.get("id")
    print(f"Followers: {profile.get('follower_count', 0):,}")

    print("Fetching recent posts...")
    posts = get_recent_posts(user_id)

    result = calculate_engagement(profile, posts)
    if not result:
        print("Could not calculate engagement (no posts or followers).")
        return

    print(f"\n--- Engagement Report for @{result['username']} ---")
    print(f"Followers: {result['followers']:,}")
    print(f"Posts analyzed: {result['posts_analyzed']}")
    print(f"Total likes: {result['total_likes']:,}")
    print(f"Total comments: {result['total_comments']:,}")
    print(f"Average engagement rate: {result['avg_engagement_rate']}%")
    print(f"\nTop posts by engagement:")
    for p in result["per_post"][:5]:
        print(
            f"  {p['shortcode']}: {p['engagement_rate']}% "
            f"({p['likes']} likes, {p['comments']} comments)"
        )


if __name__ == "__main__":
    main()

Running It

Shell
pip install requests
python engagement.py natgeo

Example output:

Output
Fetching profile: @natgeo
Followers: 284,193,203
Fetching recent posts...

--- Engagement Report for @natgeo ---
Followers: 284,193,203
Posts analyzed: 12
Total likes: 4,231,892
Total comments: 18,432
Average engagement rate: 0.124%

What’s a Good Engagement Rate?

General benchmarks:

NatGeo at 0.12% looks low in percentage terms but represents millions of interactions per post at their scale.

Variations

Weighted engagement

Count comments as 2× likes, since commenting requires more effort:

Python
weighted_rate = (likes + comments * 2) / followers * 100

Engagement by reach

Some marketers prefer (interactions / impressions) × 100. This requires data from the account owner’s Instagram Insights, not public API data.

No Script? Use the Free Tool

If you don’t want to run code, GramScraper’s free engagement calculator does this in the browser — paste a username, get the rate. No signup required.

The script gives you more control: batch processing, custom formulas, CSV export, and integration into your own tools. The API documentation covers all available endpoints.

Test GramScraper with 100 free credits

Use real public Instagram inputs, inspect the response, and estimate your endpoint mix before buying a pack.

Get an API key

Or review all GramScraper packs and the API documentation.