Back to use cases

    Use case / DEVELOPERS / Python 3 / Published

    Read public Instagram data in Python

    Use the Instagram API in Python to read public profiles, posts, comments and hashtag media. Follow a CLI quickstart with cursor paging and measured costs.

    Profile, post and hashtag inputs flowing through Desearch into JSON output

    This Instagram API quickstart helps developers read public profiles, posts, comments and hashtag media with Python and one Desearch key. This page shows a stored sample; there is no hosted demo. The CLI uses the Python standard library.

    The problem

    An app may need a public profile, a post's comments or media under a hashtag. Each task needs a clear request and a usable JSON response. Lists also need paging, date handling and a way to record the cost of each call.

    What the app does

    • Reads public profiles, profile posts and individual media.
    • Fetches comments and hashtag media, and searches for profiles.
    • Prints JSON to stdout and per-call status, time, item count and cost to stderr.
    • Adds normalized dates and leaves commenter identities out by default.
    • Supports a page limit and an estimated cost limit for list requests.

    The example reads public data. It does not post content, send direct messages or access private accounts.

    How it works

    1. Choose a command. The CLI accepts profile, posts, media, comments, hashtag or search. List counts range from 1 to 100. Paged commands accept 1 to 5 pages.
    2. Authenticate. The client loads a Desearch key from the environment or a key file. Requests include Authorization and User-Agent headers.
    3. Call the route. Profile search sends a JSON body with query and count. Other commands use GET requests. Comments use the shortcode from the post URL.
    4. Read the next page. Posts, comments and hashtag media use x-desearch-next-cursor from the response header. Send it unchanged as cursor on the same route and target. Search returns one page.
    5. Normalize and record. The CLI adds created_at in ISO UTC and retains created_raw. It records X-Desearch-Cost-Usd. The default --max-cost is $0.10; list paging stops before a call whose estimate would exceed it.

    Sort collected posts by created_at when you need newest first. Use the shortcode to match posts across routes. For like and comment counts, use profile posts or hashtag media.

    The code

    This verbatim excerpt from ig.py loads the API key. It relies on Path, os and core imported in the full file.

    PYTHON
    def api_key(key_file=None):
        path = key_file or os.environ.get('DESEARCH_API_KEY_FILE')
        try:
            key = Path(path).read_text().strip() if path else os.environ.get('DESEARCH_API_KEY', '').strip()
        except OSError as exc:
            raise core.InputError(f'cannot read API key file: {exc.strerror}') from None
        if not key:
            raise core.InputError('provide --key-file, DESEARCH_API_KEY_FILE or DESEARCH_API_KEY')
        return key

    The following verbatim Python example from the source README fetches one posts page and reads its cursor header:

    PYTHON
    import json
    import os
    from urllib.request import Request, urlopen
    
    request = Request(
        "https://api.desearch.ai/desearch/instagram/profile/natgeo/posts?count=3",
        headers={
            "Authorization": os.environ["DESEARCH_API_KEY"],
            "User-Agent": "my-app/1.0",
        },
    )
    with urlopen(request, timeout=60) as response:
        posts = json.load(response)
        cursor = response.headers.get("x-desearch-next-cursor")
    for post in posts:
        print(post["shortcode"], post["createTime"])
    print("x-desearch-next-cursor:", cursor)

    View the code

    Endpoints

    • GET /desearch/instagram/profile/{username}
    • GET /desearch/instagram/profile/{username}/posts
    • GET /desearch/instagram/media/{id}
    • GET /desearch/instagram/comments/{shortcode}
    • GET /desearch/instagram/hashtag/{tag}
    • POST /desearch/instagram/search

    Example output

    This contiguous field excerpt comes from samples/posts-natgeo.json. The stored sample fetched one page with three posts. The cursor text is a placeholder in the source sample, not a reusable cursor.

    JSON
      "count_requested": 3,
      "pages_fetched": 1,
      "returned": 3,
      "next_cursor": "<opaque cursor from the x-desearch-next-cursor header>",
      "cost_usd": 0.00621,
      "calls": 1,

    This excerpt omits post content and account identities. It is a fragment of the stored JSON object.

    Run it yourself

    Get the Python examples and open the quickstart folder. These commands are copied from its README:

    SH
    git clone https://github.com/Desearch-ai/desearch-py-examples
    cd desearch-py-examples/instagram-api-quickstart

    Create an API key in the console. Set DESEARCH_API_KEY in your environment, set DESEARCH_API_KEY_FILE to a private file, or pass --key-file before the command. No extra Python packages are needed for the CLI.

    These source README commands read a public brand profile, fetch two posts pages and search profiles:

    SH
    python3 ig.py profile natgeo
    python3 ig.py posts natgeo --count 3 --pages 2
    python3 ig.py search "national geographic" --count 3

    Use your own public target when adapting the commands. Pass --count and --pages to limit collection. Add --max-cost to set the list request estimate limit. Keep credentials private and review output before sharing it.

    What it costs

    On 2026-10-26, one profile call cost $0.00207 and the first three-post page cost $0.00621. These figures come from X-Desearch-Cost-Usd response headers. The calls took 14.08 and 15.49 seconds respectively.

    The same dated measurements recorded $0.00207 per call for profile and media lookup, and $0.00207 per returned item for posts, hashtag media, comments and search. These are measured observations, not guaranteed timings or current price quotes. Check pricing before running a larger collection.

    Ideas to extend it

    • Save collected JSON with request parameters and per-call cost records.
    • Sort normalized post dates before building a recent-post report.
    • Combine public profile and post fields into a local analysis script.
    • Add a review step before exporting comment text to a shared report.

    Use with AI agents

    Point an MCP client at the hosted Desearch server. Replace the placeholder with a key from the console. Do not commit the key.

    JSON
    {
      "mcpServers": {
        "desearch": {
          "url": "https://mcp.desearch.ai/mcp",
          "headers": {
            "Authorization": "Bearer <key>"
          }
        }
      }
    }

    Prompt you can paste for this example:

    Build a Python CLI for public Instagram data using Desearch. Read the key from DESEARCH_API_KEY or a private key file. Use GET /desearch/instagram/profile/{username}, GET /desearch/instagram/profile/{username}/posts, GET /desearch/instagram/media/{id}, GET /desearch/instagram/comments/{shortcode}, GET /desearch/instagram/hashtag/{tag} and POST /desearch/instagram/search. Set Authorization and User-Agent headers. Read x-desearch-next-cursor from response headers and send cursor unchanged on the same route and target. Search is single-page. Print JSON, normalize dates and record X-Desearch-Cost-Usd per call. Omit commenter identities by default. Do not invent missing fields or claim the first posts page is the newest.

    Build your own example.

    Give your agents access to web and social search. Get an API key to start building, or talk to us about your integration.

    Read docs