How to Automate Instagram with Instagrapi: A Python Developer’s Guide

Learn how to automate Instagram using Python's Instagrapi library: from secure login and post interactions to safe automation practices. Discover how API teams can leverage Apidog for superior API documentation and collaboration.

Mark Ponomarev

Mark Ponomarev

30 January 2026

How to Automate Instagram with Instagrapi: A Python Developer’s Guide

Apidog for Enterprise

On-Premises Deploy

SSO & RBAC

SOC 2 Compliant

Explore Apidog Enterprise

Automating Instagram tasks can save engineering teams hours of manual work—whether you're managing a brand account, building social analytics, or experimenting with new API-driven workflows. The instagrapi Python library lets you interact directly with Instagram’s backend, mimicking the official mobile app for fast, reliable automation. Unlike browser-dependent tools, instagrapi operates purely in Python, enabling headless operation and seamless integration into developer toolchains.

In this guide, you’ll learn how to set up instagrapi, securely authenticate, interact with users and posts, upload content, and follow best practices for safe, effective Instagram automation. Throughout, we’ll also highlight how tools like Apidog can supercharge your API development workflow, providing beautiful documentation and a collaborative platform for your team.

💡 Want a robust API testing tool with beautiful API documentation? Need an all-in-one platform for maximum developer productivity? Apidog delivers everything your team needs and even replaces Postman at a more affordable price!

button

Setting Up Instagrapi on Your System

Before you begin, ensure you have Python 3.9 or newer installed. Check your version in the terminal:

python --version
python3 --version

To install instagrapi, use pip:

pip install instagrapi
# or, if using python3 specifically:
python3 -m pip install instagrapi

Tip: Use a virtual environment for project isolation:

python3 -m venv insta_env
source insta_env/bin/activate  # On Windows: insta_env\Scripts\activate
pip install instagrapi

Securely Logging in to Instagram

For any automation, authentication is essential. Instagrapi’s Client class handles login securely.

from instagrapi import Client
import os

cl = Client()

INSTAGRAM_USERNAME = os.getenv("INSTA_USERNAME", "your_insta_username")
INSTAGRAM_PASSWORD = os.getenv("INSTA_PASSWORD", "your_insta_password")

try:
    cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
    print(f"Login successful as @{INSTAGRAM_USERNAME}!")
except Exception as e:
    print(f"Login failed: {e}")

Best Practice:
Never hardcode credentials. Use environment variables or secret managers.

If your account uses 2FA, pass the code during login:

cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD, verification_code="YOUR_2FA_CODE")

Saving and Reusing Sessions

Logging in repeatedly can trigger Instagram’s security checks. Instead, save your session after the first login:

SESSION_FILE_PATH = "my_active_session.json"

if os.path.exists(SESSION_FILE_PATH):
    cl.load_settings(SESSION_FILE_PATH)
    try:
        cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
        cl.get_timeline_feed()
        print("Session loaded and confirmed.")
    except Exception:
        print("Session invalid. Logging in fresh.")
        cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
        cl.dump_settings(SESSION_FILE_PATH)
else:
    cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
    cl.dump_settings(SESSION_FILE_PATH)

This approach minimizes login attempts and maintains session continuity.


Core Instagram Automation Tasks with Instagrapi

Once authenticated, the Client object (cl) allows you to automate a variety of Instagram activities.

Fetching User Information

You can retrieve public user details, follower counts, and bios:

target_user = "instagram"
user_id_num = cl.user_id_from_username(target_user)
user_details = cl.user_info_by_username(target_user)
print(f"@{user_details.username} - {user_details.follower_count} followers")
print(f"Bio: {user_details.biography[:50]}...")

Interacting with Posts (Media)

Posts are called “media” in instagrapi. Here’s how to fetch details and interact:

example_post_url = "https://www.instagram.com/p/C_q9Jg1NAn1/"
media_pk_val = cl.media_pk_from_url(example_post_url)
media_details = cl.media_info(media_pk_val)

print(f"Post by @{media_details.user.username}, {media_details.like_count} likes")
print(f"Caption: {media_details.caption_text[:60]}...")

# To like a post:
media_id_str = cl.media_id(media_pk_val)
cl.media_like(media_id_str)

# To comment:
cl.media_comment(media_id_str, text="Nice post!")

Caution:
Programmatic liking/commenting can trigger spam detection if overused. Always add delays and limit automation.


Uploading Content to Instagram

Instagrapi supports posting images, videos, albums, and stories programmatically.

Uploading a Photo

from pathlib import Path

image_path = Path("your_image.jpg")
caption = "Automated upload via Instagrapi! #Python #API"

if image_path.exists() and image_path.suffix.lower() == ".jpg":
    uploaded_photo = cl.photo_upload(image_path, caption)
    print(f"Photo uploaded: https://www.instagram.com/p/{uploaded_photo.code}/")
else:
    print("Please provide a valid JPG file path.")

Uploading a Story

Stories typically use a 9:16 aspect ratio.

story_image_path = Path("your_story_image.jpg")

if story_image_path.exists() and story_image_path.suffix.lower() == ".jpg":
    uploaded_story = cl.photo_upload_to_story(
        story_image_path,
        caption="Automated Instagram Story!"
    )
    print(f"Story uploaded! PK: {uploaded_story.pk}")
else:
    print("Provide a valid 9:16 JPG for your story.")

You can enhance stories by adding mentions or links using StoryMention and StoryLink objects.


Best Practices for Safe Instagram Automation

To keep your account safe and your automation effective:


Example: Liking Recent Posts by Hashtag

Here’s a practical automation: liking recent posts for a specific hashtag. Use cautiously and in moderation.

target_hashtag = "pythonprogramming"
number_of_posts_to_like = 1

recent_media = cl.hashtag_medias_recent(target_hashtag, amount=number_of_posts_to_like * 2)
liked_count = 0

for media_item in recent_media:
    if liked_count >= number_of_posts_to_like:
        break
    if not media_item.has_liked:
        media_id_str = cl.media_id(media_item.pk)
        cl.media_like(media_id_str)
        liked_count += 1
        time.sleep(random.uniform(15, 25))
print(f"Total liked: {liked_count}")

Note:
Overusing likes or comments can result in account restrictions.


Extending Your Automation: Documentation & Collaboration

Instagrapi offers a deep API surface. For advanced use cases, consult the official GitHub documentation. As your automation grows, managing and documenting your internal APIs becomes critical. Apidog makes it easy to generate beautiful API documentation and provides an all-in-one platform for collaborative API development, replacing Postman at a more affordable price.

button

Conclusion

Instagrapi unlocks powerful Instagram automation for Python developers and engineering teams. By following the practices above, you can automate posting, engagement, and data collection workflows while keeping your account secure and compliant.

For teams building API-driven products or internal tools, integrating solutions like Apidog can streamline API design, testing, and documentation—elevating productivity and collaboration.

Explore more

Kimi K3 vs Kimi K2.7 Code: What Actually Changed

Kimi K3 vs Kimi K2.7 Code: What Actually Changed

Kimi K3 vs Kimi K2.7 Code compared: the jump in scale, the new attention architecture, 1M context, pricing shifts, and a clear migrate-or-stay decision guide.

17 July 2026

An Open Model Just Beat Claude Opus 4.8 on Every Benchmark Moonshot Published

An Open Model Just Beat Claude Opus 4.8 on Every Benchmark Moonshot Published

Kimi K3 beat Claude Opus 4.8 on all five of Moonshot's launch benchmarks, at a fraction of the cost, with open weights due July 27. Here's what it means.

17 July 2026

Kimi K3 vs GPT-5.6 Sol: Open Weights Meets the Frontier

Kimi K3 vs GPT-5.6 Sol: Open Weights Meets the Frontier

Kimi K3 vs GPT-5.6 Sol compared: Sol leads on top-end quality, K3 wins on open weights, 1M context, and price. Full comparison table and decision matrix.

17 July 2026

Practice API Design-first in Apidog

Discover an easier way to build and use APIs

How to Automate Instagram with Instagrapi: A Python Developer’s Guide