instagrapi Documentation

repository·master·Indexed 27 days ago

https://github.com/subzeroid/instagrapi

A fast and effective unofficial Instagram Private API wrapper for Python (version 2.18.11). It combines public web and private mobile API flows to support automation for users, media, stories, and direct messages. Features include session persistence, real-time MQTT for DMs, FBNS push notifications, and video upload capabilities.

Tokens
44.5K
Snippets
97
Records
204
Agent score
90%

What's inside instagrapi

  1. Overview of instagrapi Interaction types

    master

    instagrapi categorizes its capabilities into several interaction types. These allow you to control various aspects of Instagram, including media, user data, account settings, and direct messaging. Key interaction categories include:

    • Media: Handling Photos, Videos, Albums, IGTV, Reels, and Stories.
    • Account & User: Managing private account info (email, phone) and public user data.
    • Direct Messaging: Managing DirectThread and DirectMessage.
    • Stories: Advanced story interactions including StoryLink, StoryLocation, StoryMention, StoryHashtag, and StorySticker.
    • Social Features: Interacting with Comment, Hashtag, Location, Highlight, and Note.
    • Security: Using TOTP helpers for 2FA (Google Authenticator style).
  2. Choose the right library for your needs

    master

    Depending on your requirements, you might consider these alternatives:

    • Async Support: Use aiograpi if you require an asynchronous Python implementation.
    • Other Languages: Use instagrapi-rest for non-Python environments.
    • Download Only: If you only need to download content without automation, consider Instaloader.
    • Hosted Infrastructure: For production-grade hosted Instagram API infrastructure, use HikerAPI.
  3. Available example scripts and their purposes

    master

    The instagrapi repository includes several example scripts for common automation tasks:

    ScriptPurpose
    public_lookup.pyPublic profile lookup with optional public_transport="curl"
    download_user_media.pyLogin, list recent media for a username, and download photos/videos/albums
    monitor_user_content.pyPoll a small set of users for new posts and stories using a saved session
    upload_media.pyUpload a feed photo, feed video, Reel, or Trial Reel
    upload_story.pyUpload a photo or video story, optionally with a link sticker
    direct_message.pySend a Direct text message to user IDs or thread IDs
    handle_exception.pyCentralized exception handling for challenges, relogin, and rate limits
  4. Manage Instagram Direct Messages and Threads

    master

    Use the direct_* methods to interact with Instagram Direct. You can list threads, send messages, manage group threads, and handle media sharing.

    Key Capabilities:

    • Inbox Management: List threads using direct_threads(), check pending requests with direct_requests(), or view the pending inbox with direct_pending_inbox().
    • Messaging: Send text via direct_send() or direct_answer(). Send media (photos, videos, voice) using direct_send_photo(), direct_send_video(), or direct_send_voice().
    • Thread Control: Create group threads with direct_thread_create(), add users with direct_thread_add_users(), or update titles with direct_thread_update_title().
    • Reactions: React to messages using direct_send_reaction() or use direct_message_like()/direct_message_unlike() for heart reactions.
    • Moderation: Mute/unmute threads or video calls using direct_thread_mute() and direct_thread_unmute().
  5. Access advanced tutorials and guides

    master

    Comprehensive hands-on guides for instagrapi are available at instagrapi.com/guides. Key topics include:

    • Authentication: Login flows, 2FA, and session persistence (File, Redis, Postgres).
    • Scraping & Media: Downloading stories, uploading photos, and setting up scrapers.
    • Infrastructure: Configuring proxies (HTTP, SOCKS5, residential) and framework integrations (Django, FastAPI, Celery, Docker, AWS Lambda).
    • Error Handling: Deep dives into BadPassword and other common errors.
  6. Handle Bloks Two-Factor Authentication Flow

    master

    Some Instagram accounts use the newer CAA/Bloks two-factor flow. While Client.login(..., verification_code="...") attempts to handle this automatically by retrying through the Bloks flow if a two_step_verification_context is provided, you can also drive the flow manually using low-level helpers.

    Automatic Login with Backup Codes

    If you have an 8-digit backup code, pass it directly to the login method. If a two_step_verification_context is present, instagrapi will automatically select the Bloks backup_codes challenge.

    cl.login(USERNAME, PASSWORD, verification_code="12345678")

    Manual Bloks Verification Steps

    To manually drive the Bloks flow, you need the context string from the Instagram login challenge response. Use the following sequence based on the verification method:

    TOTP

    1. cl.bloks_two_step_verification_entrypoint(context)
    2. cl.bloks_two_step_verification_method_picker(context)
    3. cl.bloks_two_step_verification_select_method(context, selected_method="totp")
    4. cl.bloks_two_step_verification_verify_code(context, code, challenge="totp")

    SMS

    1. cl.bloks_two_step_verification_select_method(context, selected_method="sms")
    2. cl.bloks_two_step_verification_verify_code(context, "123456", challenge="sms")

    Backup Codes

    1. cl.bloks_two_step_verification_select_method(context, selected_method="backup_codes")
    2. cl.bloks_two_step_verification_enter_backup_code(context)
    3. cl.bloks_two_step_verification_verify_code(context, "12345678", challenge="backup_codes")

    Applying Bloks Login Results

    After a successful verification, use bloks_extract_login_response to get the payload and bloks_apply_login_response to apply the cookies and authorization data to your client session.

    from instagrapi import Client
    
    cl = Client()
    context = "<two_step_verification_context>"
    
    # Example: Manual TOTP flow
    cl.bloks_two_step_verification_entrypoint(context)
    cl.bloks_two_step_verification_method_picker(context)
    cl.bloks_two_step_verification_select_method(context, selected_method="totp")
    
    code = cl.totp_generate_code("<totp seed>")
    result = cl.bloks_two_step_verification_verify_code(context, code, challenge="totp")
    
    # Apply the successful login to the client
    login_payload = cl.bloks_extract_login_response(result)
    cl.bloks_apply_login_response(login_payload)
  7. Handle exceptions centrally using a custom handler

    master

    Instead of wrapping every API call in try-except blocks, you can assign a custom function to Client.handle_exception. This allows you to centrally manage errors like login requirements, challenges, and throttling.

    Common exceptions to handle include:

    • LoginRequired: Trigger client.relogin() to refresh the session.
    • ChallengeRequired: Attempt to resolve challenges using client.challenge_resolve(client.last_json).
    • ClientThrottledError: Indicates an HTTP 429; you should implement backoff logic.
    • FeedbackRequired: Indicates Instagram has blocked an action; check the feedback_message in client.last_json to determine the severity.
    • BadPassword: Be cautious; Instagram may return this for risky IP/proxy states even if the password is correct. Avoid immediate retry loops.
    • PleaseWaitFewMinutes: Indicates a temporary rate limit.
    import logging
    from instagrapi import Client
    from instagrapi.exceptions import (
        BadPassword,
        ReloginAttemptExceeded,
        ChallengeRequired,
        SelectContactPointRecoveryForm,
        RecaptchaChallengeForm,
        FeedbackRequired,
        PleaseWaitFewMinutes,
        LoginRequired,
        ClientThrottledError,
        DirectMessageRequestsDisabled,
    )
    from instagrapi.utils import json_value
    
    logger = logging.getLogger(__name__)
    
    
    def handle_exception(client: Client, e: Exception):
        if isinstance(e, BadPassword):
            client.logger.exception(e)
            if client.relogin_attempt > 0:
                raise ReloginAttemptExceeded(e)
            raise e
        elif isinstance(e, LoginRequired):
            client.logger.exception(e)
            client.relogin()
            return True
        elif isinstance(e, ChallengeRequired):
            api_path = json_value(client.last_json, "challenge", "api_path")
            if api_path == "/challenge/":
                logger.warning("Generic challenge flow requires manual handling or a custom resolver")
            else:
                try:
                    client.challenge_resolve(client.last_json)
                except ChallengeRequired as e:
                    raise e
                except (ChallengeRequired, SelectContactPointRecoveryForm, RecaptchaChallengeForm) as e:
                    raise e
            return True
        elif isinstance(e, FeedbackRequired):
            message = client.last_json.get("feedback_message", "")
            if "This action was blocked. Please try again later" in message:
                logger.warning("Action blocked by Instagram: %s", message)
            elif "We restrict certain activity to protect our community" in message:
                logger.warning("Temporary activity restriction: %s", message)
            elif "Your account has been temporarily blocked" in message:
                logger.warning("Temporary account block: %s", message)
        elif isinstance(e, ClientThrottledError):
            logger.warning("HTTP 429 from Instagram, back off and review proxy/account pressure")
        elif isinstance(e, PleaseWaitFewMinutes):
            logger.warning("Please wait before retrying: %s", e)
        elif isinstance(e, DirectMessageRequestsDisabled):
            logger.warning("Recipient does not accept new Direct message requests: %s", e)
        raise e
    
    
    cl = Client()
    cl.handle_exception = handle_exception
    cl.login(USERNAME, PASSWORD)
  8. Distinguish between Public and Private requests

    master

    When using instagrapi, methods are categorized by how they interact with Instagram's infrastructure:

    • Public Web Methods: Identified by the _gql suffix (Instagram GraphQL). These are opportunistic and not guaranteed to work, as Instagram can change or block public web flows independently of the library. Some helpers use doc_id queries to replace legacy query_hash endpoints.
    • Private (Authorized) Methods: Identified by the _v1 suffix. These use the mobile API and require an authenticated session.

    Many high-level helpers are designed to attempt a public/web path first and will fallback to a private/authenticated path when appropriate for the current session.

  9. Implement session persistence with Client

    master

    To avoid repeated password logins and reduce the risk of account flags, use session persistence. You can save the client settings to a file after a successful login using dump_settings() and reload them in subsequent runs using load_settings().

    from instagrapi import Client
    
    # Initial login and saving session
    cl = Client()
    cl.login(USERNAME, PASSWORD)
    cl.dump_settings("session.json")
    
    # Subsequent run using saved session
    cl = Client()
    cl.load_settings("session.json")
    cl.login(USERNAME, PASSWORD)
  10. Use curl transport for public web endpoints

    master

    For public web endpoints that are sensitive to browser TLS fingerprints, you can use the optional curl transport instead of the default requests transport.

    1. Install the dependency:
    pip install "instagrapi[curl]"
    1. Opt-in in your code:
    cl = Client(public_transport="curl", public_transport_impersonate="chrome136")

    Note: This only affects public_transport. Private mobile API requests will continue to use the regular mobile session.