instagrapi

2.3.0 · active · verified Wed Apr 15

instagrapi is a fast and effective Python wrapper for the Instagram Private API, allowing developers to automate various Instagram interactions like posting, fetching data, and managing accounts. As of version 2.3.0, it continues to be actively maintained with frequent minor and patch releases to adapt to Instagram's ever-changing internal API.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `instagrapi.Client`, handle session loading and saving for persistent login, and perform a basic action like fetching user information. It uses environment variables for secure credential management.

import os
from instagrapi import Client

# It's highly recommended to use environment variables for sensitive data
USERNAME = os.environ.get('INSTA_USERNAME', '')
PASSWORD = os.environ.get('INSTA_PASSWORD', '')
SETTINGS_PATH = os.environ.get('INSTA_SETTINGS_PATH', 'instagrapi_settings.json')

if not (USERNAME and PASSWORD):
    print("Warning: INSTA_USERNAME and INSTA_PASSWORD environment variables not set.")
    print("This quickstart will not be able to log in without credentials.")
    # For demonstration, we'll proceed but it will fail at login

cl = Client()

# Attempt to load existing session settings to avoid re-logging in
if os.path.exists(SETTINGS_PATH):
    cl.load_settings(SETTINGS_PATH)
    print("Existing session settings loaded successfully.")
else:
    print("No existing session settings found, attempting to log in...")

# Ensure client is logged in
if not cl.is_logged_in:
    try:
        print(f"Attempting to log in as {USERNAME}...")
        cl.login(USERNAME, PASSWORD)
        cl.dump_settings(SETTINGS_PATH) # Save settings for future use
        print("Logged in successfully and session settings dumped.")
    except Exception as e:
        print(f"Login failed: {e}")
        print("Common reasons: incorrect credentials, 2FA required (handle `ChallengeRequired` exception), IP ban, or Instagram API changes.")
        exit(1)

# Example: Get user info for a public account (e.g., 'instagram')
try:
    user_info = cl.user_info_by_username("instagram")
    print(f"\nFetched info for 'instagram':")
    print(f"  User ID: {user_info.pk}")
    print(f"  Followers: {user_info.follower_count}")
except Exception as e:
    print(f"Could not fetch user info for 'instagram': {e}")
    print("This might happen if you are rate-limited or the API call has changed.")

view raw JSON →