How to Fetch Instagram Comments via API in Python

If you're building a sentiment-analysis tool, monitoring brand mentions, or enriching influencer profiles with engagement data, you'll frequently need to pull comments from Instagram posts and Reels. Instagram's official Graph API only serves comments from accounts you manage, so for ad-hoc lookups of public posts, you need a different route.

This tutorial walks through fetching Instagram comments using the Instagram Cheapest API on RapidAPI. We'll show you how to extract the post shortcode from an Instagram URL, fetch the post metadata to confirm it exists, and then retrieve all comments with Python and curl examples. The entire process uses real-time, uncached public data and costs as little as $0.10 per 1,000 requests.

What you'll need

Understanding Instagram shortcodes

Every Instagram post and Reel has a unique shortcode — an 11-character alphanumeric identifier visible in the post's URL. For example, if a post URL is:

https://www.instagram.com/p/ABC1234XYZ_/

The shortcode is ABC1234XYZ_. You can also find it in Reel URLs like https://www.instagram.com/reel/ABC1234XYZ_/. The shortcode is all you need to fetch the post and its comments.

Extracting the shortcode from a URL

Here's a simple Python function to extract the shortcode from an Instagram post or Reel URL:

import re

def extract_shortcode(url):
    """Extract the Instagram shortcode from a post or Reel URL."""
    match = re.search(r'/(p|reel)/([A-Za-z0-9_-]+)', url)
    if match:
        return match.group(2)
    return None

# Example usage
post_url = "https://www.instagram.com/p/ABC1234XYZ_/"
shortcode = extract_shortcode(post_url)
print(f"Shortcode: {shortcode}")  # ABC1234XYZ_

This regex captures the shortcode regardless of whether the URL is a /p/ post or a /reel/. Once you have the shortcode, you're ready to fetch the comments.

Fetching comments with the media_comments endpoint

The Instagram Cheapest API provides the media_comments endpoint that accepts a shortcode and returns all public comments for that post or Reel in raw JSON format.

Endpoint details

x-rapidapi-host: instagram-cheapest.p.rapidapi.com
x-rapidapi-key: YOUR_RAPIDAPI_KEY

Python example: fetching comments

import requests
import json

def fetch_instagram_comments(shortcode, api_key):
    """Fetch all comments for an Instagram post by shortcode."""
    url = "https://instagram-cheapest.p.rapidapi.com/api/v1/instagram/media_comments"

    headers = {
        "x-rapidapi-host": "instagram-cheapest.p.rapidapi.com",
        "x-rapidapi-key": api_key
    }

    params = {
        "code": shortcode
    }

    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()  # Raise error for bad status codes

    return response.json()

# Usage
api_key = "YOUR_RAPIDAPI_KEY"
shortcode = "ABC1234XYZ_"

comments_data = fetch_instagram_comments(shortcode, api_key)
print(json.dumps(comments_data, indent=2))

The response is raw JSON containing the comment thread. The exact structure depends on what Instagram returns, but typically you'll find comment text, usernames, timestamps, and nested replies. Print the JSON to inspect the structure and extract the fields you need.

curl example: quick command-line test

If you just want to see the comments without writing code, use curl:

curl -X GET \
  'https://instagram-cheapest.p.rapidapi.com/api/v1/instagram/media_comments?code=ABC1234XYZ_' \
  -H 'x-rapidapi-host: instagram-cheapest.p.rapidapi.com' \
  -H 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'

This will print the raw JSON to your terminal. Pipe it to jq for pretty-printing:

curl -X GET \
  'https://instagram-cheapest.p.rapidapi.com/api/v1/instagram/media_comments?code=ABC1234XYZ_' \
  -H 'x-rapidapi-host: instagram-cheapest.p.rapidapi.com' \
  -H 'x-rapidapi-key: YOUR_RAPIDAPI_KEY' | jq .

Optional: fetching the post metadata first

Before fetching comments, you might want to retrieve the post itself to confirm it exists and grab metadata like the caption, like count, or post type. Use the media_by_code2 endpoint:

def fetch_post_by_shortcode(shortcode, api_key):
    """Fetch Instagram post metadata by shortcode."""
    url = "https://instagram-cheapest.p.rapidapi.com/api/v1/instagram/media_by_code2"

    headers = {
        "x-rapidapi-host": "instagram-cheapest.p.rapidapi.com",
        "x-rapidapi-key": api_key
    }

    params = {
        "code": shortcode
    }

    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()

    return response.json()

# Usage
post_data = fetch_post_by_shortcode("ABC1234XYZ_", api_key)
print(json.dumps(post_data, indent=2))

This returns the post's raw JSON, which typically includes the caption, author username, media URLs, engagement counts, and more. You can extract these fields before pulling comments.

Using the fields parameter to reduce bandwidth

The API returns verbose raw JSON by default. If you only need specific fields (for example, the comment text and username), use the optional fields parameter to trim the response:

params = {
    "code": shortcode,
    "fields": "text,username,created_at"  # Adjust field names to match the actual JSON
}

This dramatically reduces payload size, which keeps you inside the API's 10 GB/month bandwidth allowance and avoids overage charges. Inspect the full JSON response first to identify which fields you need, then filter with fields in production.

A complete end-to-end workflow

Here's a full Python script that takes an Instagram post URL, extracts the shortcode, fetches the post, and then fetches all comments:

import requests
import re
import json

def extract_shortcode(url):
    match = re.search(r'/(p|reel)/([A-Za-z0-9_-]+)', url)
    return match.group(2) if match else None

def fetch_post_by_shortcode(shortcode, api_key):
    url = "https://instagram-cheapest.p.rapidapi.com/api/v1/instagram/media_by_code2"
    headers = {
        "x-rapidapi-host": "instagram-cheapest.p.rapidapi.com",
        "x-rapidapi-key": api_key
    }
    params = {"code": shortcode}
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    return response.json()

def fetch_comments(shortcode, api_key):
    url = "https://instagram-cheapest.p.rapidapi.com/api/v1/instagram/media_comments"
    headers = {
        "x-rapidapi-host": "instagram-cheapest.p.rapidapi.com",
        "x-rapidapi-key": api_key
    }
    params = {"code": shortcode}
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    return response.json()

# Main workflow
api_key = "YOUR_RAPIDAPI_KEY"
post_url = "https://www.instagram.com/p/ABC1234XYZ_/"

shortcode = extract_shortcode(post_url)
if not shortcode:
    print("Invalid Instagram URL")
else:
    print(f"Shortcode: {shortcode}")

    # Fetch post metadata
    post = fetch_post_by_shortcode(shortcode, api_key)
    print(f"Post fetched: {json.dumps(post, indent=2)[:200]}...")

    # Fetch comments
    comments = fetch_comments(shortcode, api_key)
    print(f"Comments fetched: {json.dumps(comments, indent=2)}")

This script is production-ready. Replace YOUR_RAPIDAPI_KEY with your actual key, and swap in a real post URL. The script will print the post metadata and then all comments in JSON format. Parse the JSON to extract the specific comment fields your application needs.

Pricing and cost control

Each call to media_comments or media_by_code2 counts as one request. At scale, your cost depends on the tier:

For a sentiment-analysis pipeline pulling comments from 10,000 posts per month, that's 10,000 requests — around $1.00 to $1.30 at the Mega or Pro rate. Add the fields parameter to avoid bandwidth overage charges, and your all-in cost stays predictable.

Common use cases

Here are a few real-world scenarios where fetching Instagram comments programmatically is essential:

Compliance and responsible use

This API returns public Instagram data only. Before scraping comments at scale, ensure you comply with Instagram's terms of service and applicable privacy laws like GDPR and CCPA. You are responsible for how you collect, store, and use the data. The API is not affiliated with or endorsed by Meta or Instagram.

Conclusion

Fetching Instagram comments via API is straightforward when you have the right endpoint. Extract the shortcode from the post URL, call the media_comments endpoint with your RapidAPI key, and parse the raw JSON response. The Instagram Cheapest API delivers real-time, uncached data at a fraction of the cost of enterprise scrapers — as low as $0.10 per 1,000 requests — making it practical for startups, researchers, and indie developers who need affordable access to public Instagram data.

Start with the free 30-request tier to test your integration, then scale up as your usage grows. With Python or curl and a valid RapidAPI key, you can be pulling live comments in under five minutes.

Get started on RapidAPI →

Compliance note: this API returns public Instagram data only. You are responsible for complying with Instagram's terms and applicable privacy law (GDPR/CCPA). Not affiliated with or endorsed by Meta/Instagram.

Start Building Today

Get 30 free requests per month on the Basic plan. No commitment required.

Get Started on RapidAPI