Foothold OSINT
subzeroid/instagrapi: A Security Analyst's Field Guide

subzeroid/instagrapi: A Security Analyst's Field Guide

A practical breakdown of instagrapi for OSINT analysts: what it does, where it fits, how it compares to alternatives, and a reproducible 10-minute recipe.

OSINT Tool Deep-Dives

For: Security professionals, Enthusiasts & students

subzeroid/instagrapi: A Security Analyst’s Field Guide

Instagram’s private API is one of the richer intelligence surfaces available to an analyst right now. Follower graphs, geotags, story metadata, engagement patterns, business category flags — none of it is exposed through a public API that Meta documents or supports. Getting to it programmatically means either reverse-engineering the mobile client yourself or using a library that already did.

subzeroid/instagrapi (6,726 stars as of early 2025) is that library. It replicates the API calls an Instagram mobile app makes, returns structured JSON, and exposes a Python interface wide enough to cover most analyst use cases. This post covers what it actually does, where it slots into a collection workflow, how it compares to the other options, and a short recipe you can run in a controlled lab in under ten minutes.


What the Library Actually Does

instagrapi is not an HTML scraper. It authenticates to Instagram using a private session — cookie-based or credential-based — and fires the same API calls a real iOS or Android client would. The responses are structured JSON, parsed into Pydantic models that serialize cleanly to dicts or drop straight into a database.

Capability domains from the official repository:

Account and Profile Intelligence

Content and Media Analysis

Story and Ephemeral Content

Graph Traversal

Direct Messaging

Search and Discovery

HikerAPI Integration


Where It Fits in the Toolchain

Instagram OSINT splits into two tiers: manual browser review and automated collection. instagrapi sits firmly in the automated tier, between lightweight scrapers and full commercial intelligence platforms.

Upstream inputs: Analysts typically feed it a seed set of usernames, hashtags, or location identifiers from earlier investigative steps — a threat intel report, a cross-reference against a leaked credential dataset, or a starting point from a client brief.

Downstream outputs: Pydantic models that serialize to JSON or insert directly into a database. These integrate naturally with Maltego via custom transforms, NetworkX for Python-native graph work, or Gephi for visualization.

Defensive use cases:

Offensive OSINT use cases:


Instagram’s Terms of Service prohibit automated access without explicit permission. Using instagrapi outside of authorized contexts may violate the Computer Fraud and Abuse Act in the US, the Computer Misuse Act in the UK, and equivalent statutes elsewhere.

Legitimate contexts:

The DM and posting capabilities need particular care. Sending unsolicited messages or taking actions on accounts you do not control is out of scope for security research, full stop.


instagrapi vs. the Alternatives

instagram-scraper (arc298): Older HTML-scraping approach, no private API. Useful for light unauthenticated public data collection, but increasingly fragile as Instagram’s frontend changes and shallow in what it returns.

Selenium/Playwright-based approaches: Browser automation simulating a human session. More resilient to frontend changes than raw scraping, but slow, resource-heavy, and hard to scale. Better for one-off evidence capture than bulk collection.

Commercial OSINT platforms (Babel Street, Skopenow, Cobwebs Technologies): Enterprise-grade with legal frameworks, managed infrastructure, and support. The right choice for law enforcement or large enterprise deployments where budget and compliance requirements justify the cost. They abstract the API layer entirely, which is both a feature and a constraint.

instagrapi’s real advantage is depth combined with Python-native integration. The Pydantic model outputs make pipeline construction straightforward, and the community is active enough that the issue tracker reflects real operational experience rather than stale bug reports.

Choose instagrapi when:

Choose something else when:


10-Minute Reproducible Recipe

This walkthrough uses a test Instagram account you control. Do not run it against accounts you do not own or have explicit authorization to query.

Prerequisites

Step 1: Environment Setup

python3 -m venv osint-insta-env
source osint-insta-env/bin/activate  # Windows: osint-insta-env\Scripts\activate
pip install instagrapi

Step 2: Authenticate and Save a Session

A reusable session file avoids repeated login challenges and reduces account friction during testing.

# auth_setup.py
from instagrapi import Client
import json

cl = Client()
cl.login("your_test_username", "your_test_password")
cl.dump_settings("session.json")
print("Session saved.")

Run with: python auth_setup.py

Step 3: Load Session and Pull User Intelligence

# user_intel.py
from instagrapi import Client
import json

cl = Client()
cl.load_settings("session.json")
cl.login("your_test_username", "your_test_password")

target = "instagram"  # Replace with your authorized target username
user_info = cl.user_info_by_username(target)

output = {
    "user_id": str(user_info.pk),
    "username": user_info.username,
    "full_name": user_info.full_name,
    "biography": user_info.biography,
    "follower_count": user_info.follower_count,
    "following_count": user_info.following_count,
    "is_verified": user_info.is_verified,
    "is_business": user_info.is_business,
    "external_url": str(user_info.external_url) if user_info.external_url else None,
}

print(json.dumps(output, indent=2))

Run with: python user_intel.py

Step 4: Enumerate Recent Media with Location Data

# media_intel.py
from instagrapi import Client
import json

cl = Client()
cl.load_settings("session.json")
cl.login("your_test_username", "your_test_password")

target = "instagram"  # Replace with authorized target
user_id = cl.user_id_from_username(target)
medias = cl.user_medias(user_id, amount=10)

results = []
for media in medias:
    results.append({
        "media_id": str(media.pk),
        "media_type": media.media_type,
        "taken_at": media.taken_at.isoformat() if media.taken_at else None,
        "like_count": media.like_count,
        "comment_count": media.comment_count,
        "location_name": media.location.name if media.location else None,
        "location_lat": float(media.location.lat) if media.location else None,
        "location_lng": float(media.location.lng) if media.location else None,
    })

print(json.dumps(results, indent=2))

Run with: python media_intel.py

At this point you have a structured JSON dataset covering account metadata and recent media, with geolocation fields where Instagram populated them, ready for downstream analysis or graph ingestion.


Operational Notes

Session management matters. Instagram’s backend tracks behavioral signals. High-volume queries from a freshly created account will trigger challenges or suspensions quickly. Use aged accounts, add time.sleep() calls between requests, and configure the library’s built-in delay settings (request_timeout, delay_range) for realistic pacing. If sustained collection is the requirement, the HikerAPI integration exists for exactly that reason.

Log everything. For defensive investigations especially, maintain a complete log of queries made, timestamps, and data retrieved. If findings end up in legal proceedings or an executive briefing, an audit trail is not optional.

Handle credentials securely. Store Instagram credentials in environment variables or a secrets manager, not hardcoded in scripts. The session JSON file contains sensitive tokens and should be treated like a private key.


Where to Go From Here

The official repository is the right primary reference as the library evolves. The issue tracker reflects real operational experience from the community, which makes it more useful than the README alone.

Meta’s Platform Policy documentation describes the boundaries of authorized API use and is worth reading before deploying this in any context outside a personal test account.

For workflow context, Bellingcat’s operational guides on social media OSINT show how investigative teams actually structure network mapping and geolocation work — a useful reference for building pipelines that go beyond single-account lookups. The OSINT Framework maintained by Justin Nordine catalogs where Instagram collection fits within broader methodologies.

Run the recipe above in a lab first. Understand how the session behaves, watch what triggers friction, and build your operational procedures before pointing any of this at a production target under active engagement scope.