Back

Step by Step Guide to Building an Instagram API Integration in Python

Aug 1, 20245 minute read

Introduction

Hey there, fellow devs! Ready to dive into the world of Instagram API integration? We're going to use instagrapi, a powerful unofficial API that'll make your life way easier than dealing with the official Instagram API. Trust me, you'll thank me later.

Setup

First things first, let's get our environment ready:

pip install instagrapi

Now create a new Python project. I know you know how to do this, so I'll spare you the details.

Authentication

Alright, let's get this party started:

from instagrapi import Client client = Client() client.login(username="your_username", password="your_password")

Easy peasy, right? Just remember to keep those credentials safe!

Basic Operations

Now for the fun part. Let's fetch some data:

# Get user info user_id = client.user_id_from_username("instagram") user_info = client.user_info(user_id) # Get user's posts medias = client.user_medias(user_id, 20) # Like a post client.media_like(medias[0].id) # Comment on a post client.media_comment(medias[0].id, "Great post!")

See how smooth that is? You're already a pro!

Advanced Features

Let's kick it up a notch:

# Upload a photo client.photo_upload("path/to/photo.jpg", caption="Check out this awesome pic!") # Post a story client.photo_upload_to_story("path/to/story.jpg") # Send a DM client.direct_send("Hey there!", user_ids=[user_id])

Now you're cooking with gas!

Error Handling and Rate Limiting

Don't get too excited and hit those rate limits. Here's a quick way to handle errors and implement basic rate limiting:

import time from instagrapi.exceptions import PleaseWaitFewMinutes def rate_limited_operation(func, *args, **kwargs): try: return func(*args, **kwargs) except PleaseWaitFewMinutes: print("Rate limited. Waiting for 5 minutes...") time.sleep(300) return func(*args, **kwargs)

Use this wrapper for your API calls, and you'll be golden.

Best Practices

  1. Never hardcode your credentials. Use environment variables or a secure vault.
  2. Cache your data when possible to reduce API calls.
  3. Be a good netizen - don't abuse the API!

Example Project: Instagram Analytics Tool

Let's put it all together:

from instagrapi import Client from collections import Counter client = Client() client.login(username="your_username", password="your_password") username = "instagram" user_id = client.user_id_from_username(username) medias = client.user_medias(user_id, 50) likes = sum(media.like_count for media in medias) comments = sum(media.comment_count for media in medias) hashtags = Counter([hashtag for media in medias for hashtag in media.caption_hashtags]) print(f"Total likes: {likes}") print(f"Total comments: {comments}") print(f"Top 5 hashtags: {hashtags.most_common(5)}")

And there you have it - a simple Instagram analytics tool in just a few lines of code!

Conclusion

You've just scratched the surface of what's possible with instagrapi. The world is your oyster now! Remember to always respect Instagram's terms of service and use this power responsibly.

Keep coding, keep learning, and most importantly, have fun!