aiograpi Documentation

repository·main·Indexed 19 days ago

https://github.com/subzeroid/aiograpi

An asynchronous Python wrapper for the Instagram Private API (version 1.12.8) that does not rely on Selenium. It provides tools for research and testing, including public profile lookups, media uploads (photos, videos, Reels, stories), media downloads, and Direct Messaging via text or Realtime MQTT. The library includes a comprehensive Client for account management and detailed error handling for authentication challenges, rate limits, and proxy connectivity.

Tokens
63.2K
Snippets
165
Records
213
Agent score
62%

What's inside aiograpi

  1. Explore aiograpi documentation and usage guides

    main

    The aiograpi documentation is organized into several key areas to help you build with the Instagram API:

    • Fundamentals: Core concepts and usage guides.
    • Interactions: Detailed documentation for specific Instagram objects including:
      • Media: Publications (Photo, Video, Album, IGTV, Reels), Resource (parts of an album), and MediaOembed.
      • Users: Account (private info), User (full public data), and UserShort (lightweight public data).
      • Stories: Story, StoryLink, StoryLocation, StoryMention, StoryHashtag, StorySticker, and the StoryBuild utility.
      • Direct Messaging: DirectThread (topics) and DirectMessage.
      • Other: Hashtag, Location, Collection, Comment, Highlight, Notes, Insight, and Track.
    • Specialized Guides:
      • Captcha: Interface for solver integrations.
      • Challenge Resolver: Handling authentication challenges.
      • Platform Specifics: Notes for Pydroid (Android) and Termux.
    • Error Handling: Guidance on Exceptions and how to handle them.
  2. Understand Public vs Private API requests

    main

    aiograpi distinguishes between two types of requests to optimize for Instagram limits:

    1. Public/Graphql (_gql suffix): Anonymous requests made via the web API. These are used first to fetch media or user info.
    2. Private/Mobile (_v1 suffix): Authorized requests made via the mobile app API. These are used when a public request fails (e.g., due to a restricted video or a private account).

    Pattern for robust requests: Try the _gql method first, and if a ClientError occurs (indicating the content is restricted or private), fallback to the _v1 method.

    async def media_info(media_pk):
        try:
            return await self.media_info_gql(media_pk)
        except ClientError as e:
            # Handle restricted video or private account by falling back to private API
            return await self.media_info_v1(media_pk)
  3. Use Realtime MQTT for live events

    main

    The RealtimeClient provides an experimental connection to Instagram's MQTToT transport. It is used to receive live event callbacks instead of polling HTTP endpoints. It can also be used to publish lightweight Direct actions (text, reactions, seen state, activity status).

    Warning: Realtime MQTT support is experimental and Instagram may change this private transport without notice. For full Direct operations like sending media or managing threads, use the standard HTTP direct_* methods.

    from aiograpi import Client
    
    cl = Client()
    await cl.login(USERNAME, PASSWORD)
    
    # Connect to realtime
    rt = await cl.realtime_connect()
    
    # Use for lightweight actions
    await rt.direct_send_text(thread_id, "Hello from MQTT")
  4. Configure Public Transport for web requests

    main

    The aiograpi library uses two distinct network surfaces: private mobile API requests for authenticated flows, and public web requests for helpers like public profile and media lookups.

    By default, aiograpi uses the requests transport, which is an async HTTP transport based on httpx. This has the smallest dependency footprint.

    If you encounter rate limiting (429 errors) or TLS fingerprinting blocks on public web endpoints, you can switch to the curl transport. Note that the curl transport only affects the public web session; private mobile API requests continue to use the regular mobile session.

    from aiograpi import Client
    
    # Default behavior uses public_transport="requests"
    cl = Client()
    
    # Explicitly using curl transport with impersonation
    cl = Client(public_transport="curl", public_transport_impersonate="chrome136")
  5. Understand Manual and Bloks Redirect Challenges

    main

    Not all Instagram challenges can be solved via challenge_code_handler or change_password_handler:

    • Native Flow Challenges: If a challenge has challenge.native_flow=true and an opaque /challenge/... api_path, it is a manual checkpoint. These do not expose SMS, email, or password steps.
    • Bloks Redirects: Challenges involving bloks_action="com.bloks.www.ig.challenge.redirect.async" or a placeholder step_name="STEP_NAME" require manual confirmation via the official Instagram app or web browser on a trusted device. In these cases, aiograpi will raise a ChallengeRequired exception containing the sanitized challenge context rather than attempting an automated resolution.
  6. Retrieve comments from media

    main

    There are several ways to fetch comments depending on whether you need authenticated access, chunked pagination, or public GraphQL access.

    Authenticated Methods

    • media_comments(media_id, amount=0): Returns a list of Comment objects. Setting amount=0 retrieves all comments.
    • media_comments_chunk(media_id, max_amount, min_id=None): Returns a tuple of (List[Comment], end_cursor). Use the returned end_cursor as the min_id in subsequent calls to paginate through comments.
    • media_comment_replies(media_id, comment_id, amount=0): Retrieves replies for a specific parent comment.
    • media_comment_replies_chunk(media_id, comment_id, max_amount, min_id=None): Paginated retrieval of comment replies.

    Public GraphQL Methods

    These methods use Instagram's public web GraphQL endpoints and do not necessarily require a full session, but are still subject to rate limits (401/403/429) based on IP and fingerprinting.

    • media_comments_gql(media_pk, amount=50, max_requests=0): Get comments via the public web GraphQL doc_id endpoint.
    • media_comments_public_gql(code, amount=50, max_requests=0): Get comments using a media shortcode. This method automatically builds the required doc_id and post referer.
    # Paginated retrieval using chunks
    (comments_part1, next_min_id) = await cl.media_comments_chunk(media_id, 100)
    (comments_part2, next_min_id) = await cl.media_comments_chunk(media_id, 100, next_min_id)
    
    # Public GraphQL retrieval by shortcode
    public_comments = await cl.media_comments_public_gql("CjPUjEvDKT4", amount=40)
  7. Understand Client settings deepcopy behavior

    main

    In version 0.1.1, the Client constructor was updated to deepcopy the settings dictionary passed to it. This prevents mutations made to the original dictionary from leaking into the Client instance.

    If your code relied on the identity of the passed dictionary (cl.settings is the_dict_i_passed), you should update your logic to use cl.settings directly.

  8. Implement resumable pagination for hashtags

    main

    For resumable pagination (e.g., loading new posts every time a script runs), use hashtag_medias_paginated(). This method returns a tuple containing the list of Media objects and an end_cursor string. To fetch the next page, pass the returned cursor back into the end_cursor parameter of the next call.

    Note: For low-level access to the private/mobile API, you can use hashtag_medias_v1_chunk(), which uses a max_id instead of an end_cursor.

    # Initial request
    medias, cursor = await cl.hashtag_medias_paginated('test', amount=32, tab_key='recent')
    
    # Subsequent request using the returned cursor
    next_medias, cursor = await cl.hashtag_medias_paginated('test', amount=32, tab_key='recent', end_cursor=cursor)
  9. Understand the project dependency structure

    main

    The project uses pyproject.toml (via Setuptools) as the single source of truth for metadata and dependencies.

    • [project].dependencies: Contains the runtime dependencies required by the library.
    • [project.optional-dependencies].test: Contains the tools required for testing, linting, documentation, and local development.

    Note: Android-specific dependency pins (e.g., for Termux pydantic-core) are permitted to ensure compatibility with the mobile Python ecosystem.

  10. How to interpret field presence in aiograpi models

    main

    When working with the Pydantic models in aiograpi.types, follow these rules for field validation:

    • Required fields: These have no default value and will always be present in the model.
    • Optional fields: Marked with Optional[...], these may be absent from the Instagram response or returned as null.
    • Raw data: Fields with dict or list types are used to preserve Instagram data that is not yet stable enough for a dedicated public model.
  11. Make anonymous public calls using GQL methods

    main

    You can perform certain actions without logging in by using methods with the _gql suffix. These methods target the public web GraphQL surface. Note that methods with the _v1 suffix require an authenticated session.

    client = Client()
    user = await client.user_info_by_username_gql("instagram")
    print(user.username, user.pk)  # → "instagram", "25025320"