Automating tasks on Instagram can significantly streamline how you manage your online presence. instagrapi
is a Python library designed to help you do exactly that. It interacts directly with Instagram's own backend systems—the same ones the official mobile app uses. This direct communication makes instagrapi
fast and efficient, and it doesn't require a web browser to operate.
This guide aims to provide a clear path to getting started with instagrapi
. We'll cover how to install it, log into your Instagram account securely, perform common actions like interacting with posts and users, upload content, and touch upon essential practices to ensure your automation is safe and effective.
Want an integrated, All-in-One platform for your Developer Team to work together with maximum productivity?
Apidog delivers all your demans, and replaces Postman at a much more affordable price!
Getting Instagrapi Onto Your System
Before you can use instagrapi
, you need to install it. First, ensure you have Python installed on your computer; instagrapi
works best with Python version 3.9 or newer. You can check your Python version by opening a terminal (Command Prompt, PowerShell, or Terminal on macOS/Linux) and typing python --version
or python3 --version
.
Once Python is ready, installing instagrapi
is straightforward using pip
, Python's package installer. In your terminal, execute the following command:
pip install instagrapi
If you use python3
specifically for your Python 3 installation, you might need:
python3 -m pip install instagrapi
This command will download and install instagrapi
and any other libraries it depends on. For cleaner project management, it's often recommended to use Python virtual environments, which isolate project dependencies. You can create one with python3 -m venv your_project_name
, activate it, and then run the pip install instagrapi
command inside it.
Connecting to Your Instagram Account
To perform actions on Instagram, your script needs to log in. instagrapi
handles this process. The first step in your Python script will be to import the Client
class and create an instance of it. This Client
object will be your main tool for all interactions.
from instagrapi import Client
import os
import time
import random
cl = Client()
Now, let's log in. It's highly advisable not to hardcode your username and password directly in your script. Using environment variables is a more secure method.
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 for @{INSTAGRAM_USERNAME}. Error: {e}")
If your account has Two-Factor Authentication (2FA) enabled, which is great for security, the login
method will require an additional verification_code
parameter. You'd typically get this code from your authenticator app or an SMS and pass it during the login call: cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD, verification_code="YOUR_2FA_CODE")
.
Constantly logging in with a username and password can be inefficient and might attract unwanted attention from Instagram. A smarter approach is to save your login session after the first successful authentication and then reload this session for future script runs.
Here’s how you can manage sessions:
from instagrapi.exceptions import LoginRequired
SESSION_FILE_PATH = "my_active_session.json"
if os.path.exists(SESSION_FILE_PATH):
cl.load_settings(SESSION_FILE_PATH)
print(f"Loaded session from {SESSION_FILE_PATH}.")
try:
cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
cl.get_timeline_feed()
print("Session is valid and login successful using saved session.")
except LoginRequired:
print("Saved session was invalid. Need to perform a fresh login.")
try:
cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
cl.dump_settings(SESSION_FILE_PATH)
print("Fresh login successful, new session saved.")
except Exception as e_relogin:
print(f"Fresh login failed after invalid session: {e_relogin}")
except Exception as e_session_use:
print(f"Error while using saved session: {e_session_use}. Trying fresh login.")
try:
cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
cl.dump_settings(SESSION_FILE_PATH)
print("Fresh login successful after session error, new session saved.")
except Exception as e_fresh_fallback:
print(f"Fresh login fallback also failed: {e_fresh_fallback}")
else:
print("No session file found. Performing fresh login...")
try:
cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
cl.dump_settings(SESSION_FILE_PATH)
print(f"Fresh login successful, session saved to {SESSION_FILE_PATH}.")
except Exception as e_initial_login:
print(f"Initial fresh login failed: {e_initial_login}")
if cl.user_id:
print(f"Successfully authenticated. User ID: {cl.user_id}")
else:
print("Authentication failed. Check credentials and previous error messages.")
This combined approach attempts to use a saved session first and falls back to a fresh login if needed, saving the new session for next time.
Core Instagram Interactions with Instagrapi
Once logged in, you can start interacting with Instagram. Assume cl
is your successfully logged-in Client
object for the examples below.
Getting User Information
You can fetch public information about any Instagram user if you know their username. This includes their unique User ID (PK), full name, bio, follower counts, etc.
target_user = "instagram"
try:
user_id_num = cl.user_id_from_username(target_user)
print(f"The unique User ID for @{target_user} is {user_id_num}.")
user_details = cl.user_info_by_username(target_user)
print(f"\nDetails for @{user_details.username}:")
print(f" Followers: {user_details.follower_count}")
print(f" Bio: {user_details.biography[:50]}...")
except Exception as e:
print(f"Could not fetch info for @{target_user}. Error: {e}")
Interacting with Posts (Media)
Instagram posts are referred to as "media" in instagrapi
. To interact with a post, you usually need its media_pk
(a unique numerical ID for the post). You can get this media_pk
from the post's URL. The following example shows how to get post details. Interactions like liking or commenting are very sensitive to automation; use such features sparingly and always ethically.
example_post_url = "https://www.instagram.com/p/C_q9Jg1NAn1/"
try:
media_pk_val = cl.media_pk_from_url(example_post_url)
print(f"The media_pk for the post is: {media_pk_val}")
media_details = cl.media_info(media_pk_val)
print(f"\nPost by @{media_details.user.username} has {media_details.like_count} likes.")
print(f"Caption snippet: {media_details.caption_text[:60]}...")
string_media_id_for_action = cl.media_id(media_pk_val)
print(f"String media_id for actions (like liking/commenting): {string_media_id_for_action}")
except Exception as e:
print(f"Error interacting with post {example_post_url}. Error: {e}")
To like a post, you would use cl.media_like(string_media_id_for_action)
. To comment, you'd use cl.media_comment(string_media_id_for_action, text="Your comment")
. Always include delays (time.sleep()
) after such actions.
Uploading Contentinstagrapi
allows you to upload photos, videos, albums, and stories.
Uploading a Photo:
You'll need the path to a JPG image file. The example below outlines the structure; you'll need to provide a valid path to an image.
from pathlib import Path
image_path_to_upload = Path("your_image.jpg")
photo_caption = "My first photo upload with Instagrapi! #Python #Automation"
if image_path_to_upload.exists() and image_path_to_upload.suffix.lower() == ".jpg":
try:
uploaded_photo = cl.photo_upload(image_path_to_upload, photo_caption)
print(f"Photo uploaded! View it at: https://www.instagram.com/p/{uploaded_photo.code}/")
except Exception as e:
print(f"Photo upload failed for {image_path_to_upload}. Error: {e}")
else:
print(f"Replace 'your_image.jpg' with a valid path to a JPG file.")
Uploading a Story:
Stories often use a 9:16 aspect ratio. You can upload photos or videos. The code for uploading a photo story is similar to a regular photo post but uses photo_upload_to_story
.
from instagrapi.types import StoryMention, StoryLink
story_image_path = Path("your_story_image.jpg")
if story_image_path.exists() and story_image_path.suffix.lower() == ".jpg":
try:
uploaded_story = cl.photo_upload_to_story(
story_image_path,
caption="My Instagrapi Story!"
)
print(f"Story uploaded successfully! PK: {uploaded_story.pk}")
except Exception as e:
print(f"Story upload failed for {story_image_path}. Error: {e}")
else:
print(f"Replace 'your_story_image.jpg' with a valid path to a 9:16 JPG file for stories.")
You can add interactive elements like mentions
and links
by preparing StoryMention
or StoryLink
objects and passing them as parameters to photo_upload_to_story
.
Key Considerations for Smooth Automation
When automating Instagram actions, a few practices are crucial for reliability and to avoid issues with your account.
Introduce Delays: Human users don't perform actions instantly one after another. Your script shouldn't either. Use time.sleep(random.uniform(min_seconds, max_seconds))
between actions to mimic natural interaction patterns. instagrapi
itself has a cl.delay_range = [min, max]
setting that adds some automatic delays for certain operations.
Consider Proxies for Intensive Use: If your script makes a large number of requests, or if you manage multiple accounts from the same IP address, Instagram might limit your activity. Using a proxy server (cl.set_proxy("your_proxy_string")
) can help distribute your requests and appear as if they're coming from different locations.
Handle Potential Errors: Network issues can occur, Instagram's API might change, or you might hit a rate limit. Wrap your instagrapi
calls in try...except
blocks to catch these errors gracefully. instagrapi
has specific exceptions like RateLimitError
, UserNotFound
, MediaNotFound
, etc., which you can catch for more targeted error handling.
Use Responsibly and Ethically: Automation is powerful. Avoid spamming, respect user privacy, and don't engage in activities that violate Instagram's Terms of Service or Community Guidelines. The goal of automation should be to enhance genuine interaction or manage your presence efficiently, not to manipulate or annoy.
A Simple Automation Example: Liking Recent Posts for a Hashtag
Let's create a small script that finds recent posts for a specific hashtag and likes a few of them. This demonstrates combining several instagrapi
features. Use this example with extreme caution and only on hashtags and in quantities that align with responsible usage. This code is illustrative and aggressive use can harm your account.
target_hashtag_for_liking = "pythonprogramming"
number_of_posts_to_like = 1
try:
print(f"Fetching recent media for #{target_hashtag_for_liking}...")
recent_hashtag_media = cl.hashtag_medias_recent(target_hashtag_for_liking, amount=number_of_posts_to_like * 2)
liked_count = 0
if recent_hashtag_media:
for media_item in recent_hashtag_media:
if liked_count >= number_of_posts_to_like:
break
if not media_item.has_liked:
print(f" Attempting to like post PK {media_item.pk} by @{media_item.user.username}...")
try:
media_id_str_to_like = cl.media_id(media_item.pk)
cl.media_like(media_id_str_to_like)
liked_count += 1
print(f" Successfully liked. Liked {liked_count}/{number_of_posts_to_like} posts so far.")
time.sleep(random.uniform(15, 25))
except Exception as e_like:
print(f" Could not like post PK {media_item.pk}. Error: {e_like}")
else:
print(f" Skipping already liked post PK {media_item.pk} by @{media_item.user.username}.")
print(f"\nFinished liking script for #{target_hashtag_for_liking}. Total liked in this run: {liked_count}")
else:
print(f"No recent media found for #{target_hashtag_for_liking}.")
except Exception as e_hashtag_script:
print(f"An error occurred in the hashtag liking script: {e_hashtag_script}")
This example is for demonstration. Automating likes, especially in large numbers, can easily be flagged by Instagram. Always prioritize genuine engagement over mass automated actions.
Moving Forward with Instagrapi
instagrapi
offers a deep set of tools for interacting with Instagram. This guide has scratched the surface, showing you how to set up, log in, and perform some of the most common actions.
To truly master instagrapi
, explore its official documentation. The README.md
file on the Instagrapi GitHub repository is the best starting point, usually linking to more detailed guides and API references within its docs
folder. These resources cover many more features, advanced settings, and specific types for various Instagram objects.
Remember that the Instagram platform and its API can change, so what works today might need adjustments tomorrow. Staying updated with the instagrapi
library and community discussions can help you adapt. Happy automating, and do so responsibly!
Want an integrated, All-in-One platform for your Developer Team to work together with maximum productivity?
Apidog delivers all your demans, and replaces Postman at a much more affordable price!