# Check Instagram Profiles Before an Ad Campaign with Python

https://jsonscraper.com/blog/check-instagram-profiles-before-campaign

Author: Michael Johnson

Published: 2026-11-19T11:35:02+00:00

Updated: 2026-11-19T11:35:02+00:00

Retrieve public account details from a brief and create an exceptions report before launching a campaign

Checking Instagram accounts before launching a campaign helps catch errors in the placement list while they are still easy to fix. For example, a brief might contain a typo in a username, a duplicate account, or a profile with an unexpected follower count. Below is a small Python script that requests public data for each username, compares the response with your criteria, and saves the results for review in a CSV file.

 

## What the output looks like

 

The input is a CSV containing a list of accounts and optional expected values. The output has a separate row for each processed username: request status, profile name, verification indicator, follower, post, and following counts, plus a short list of any discrepancies found.



![Article: Check Instagram Profiles Before an Ad Campaign with Python
Summary: Incorrect usernames, extra spaces, or unsuitable profiles in a brief can go unnoticed until campaign preparations are complete. Learn how to check Instagram usernames through the documented jsonscraper endpoint and export observed discrepancies to CSV.
Image role: cover — the central idea
Section: What the output looks like
Visual subject: Editorial photo ](https://jsonscraper.com/assets/uploads/journal/2026/11/84aacded9a89d423a6289b53b549643f.png.hero.webp)

The report brings together checked profile fields and flags for manual review before the campaign launches.© jsonscraper · AI-generated

 

This report can help a marketer check contractors against a brief, or a developer build an internal check into a recurring task. It checks specific public profile fields at the time of the request; the team remains responsible for deciding whether a profile is suitable for the campaign.

 

## Which fields you can check

 

The documented Instagram API endpoint `/v1/user/by/username` accepts the required `username` parameter. In the observed response format, profile data is in the `ig` object; fields returned included `username`, `full_name`, `is_private`, `is_verified`, `media_count`, `follower_count`, `following_count`, and `biography`. Fields may not always be present, so the script below records missing values as blank rather than converting them to zero. The [Instagram API reference](https://github.com/jsonscraper/instagram-api-python/blob/main/docs/endpoints.md) lists the endpoints and parameter names.

 

The check is especially useful for criteria that can be stated explicitly: the profile must be public, its follower count must fall within a specified range, and its verification indicator must match the brief. You can save the biography for later review, but automatically comparing its text with marketing positioning would require a separate criterion.

 

## Prepare the input file

 

Create `profiles.csv` in UTF-8. The minimal version contains only usernames; leave additional expected fields blank if the brief does not specify a requirement:

 

```
username,min_followers,max_followers,verified
brand_example,5000,50000,false
creator_example,10000,,true
```

 

The `min_followers` and `max_followers` values set the bounds for the check. The `verified` field accepts `true` or `false`. Specify only the applicable criteria for each profile.

 

## Request the data and generate a report

 

Install `requests` and set the key in the process environment rather than in the source file. On macOS or Linux, the commands are:



![Article: Check Instagram Profiles Before an Ad Campaign with Python
Summary: Incorrect usernames, extra spaces, or unsuitable profiles in a brief can go unnoticed until campaign preparations are complete. Learn how to check Instagram usernames through the documented jsonscraper endpoint and export observed discrepancies to CSV.
Image role: supporting illustration 2 — a different specific aspect
Section: Request the data and generate a report](https://jsonscraper.com/assets/uploads/journal/2026/11/146a636928d29c035050cacd0aa101b8.png.hero.webp)

The diagram shows the path from a CSV account list to a report, where missing fields remain blank and matches against rules are marked separately.© jsonscraper · AI-generated illustration

 

```
python -m pip install requests
export JSONSCRAPER_INSTAGRAM_LICENSE_KEY='your-key'
```

 

Save the script below as `check_profiles.py`. It uses Python 3.8+, checks the HTTP response status, reads the `ig` payload separately, and creates `profile_check.csv`. The key is passed as the `license_key` query parameter, as specified in the service documentation.

 

```
import csv
import os
import sys
from typing import Dict, List, Optional

import requests

API_URL = "https://ig.jsonscraper.com/v1/user/by/username"
API_KEY = os.environ.get("JSONSCRAPER_INSTAGRAM_LICENSE_KEY")

if not API_KEY:
    raise SystemExit("Set JSONSCRAPER_INSTAGRAM_LICENSE_KEY")


def parse_bool(value: str) -> Optional[bool]:
    normalized = value.strip().lower()
    if normalized in ("true", "1", "yes", "да"):
        return True
    if normalized in ("false", "0", "no", "нет"):
        return False
    return None


def check_row(row: Dict[str, str]) -> Dict[str, str]:
    username = row.get("username", "").strip().lstrip("@")
    result = {
        "requested_username": username,
        "status": "",
        "returned_username": "",
        "full_name": "",
        "is_private": "",
        "is_verified": "",
        "follower_count": "",
        "media_count": "",
        "following_count": "",
        "biography": "",
        "issues": "",
    }

    if not username:
        result["status"] = "skipped_empty_username"
        result["issues"] = "empty_username"
        return result

    try:
        response = requests.get(
            API_URL,
            params={"license_key": API_KEY, "username": username},
            timeout=30,
        )
        response.raise_for_status()
        payload = response.json()
    except (requests.RequestException, ValueError) as exc:
        result["status"] = "request_error"
        result["issues"] = type(exc).__name__
        return result

    if payload.get("status") != "ok":
        result["status"] = "api_error"
        result["issues"] = "unexpected_outer_status"
        return result

    profile = payload.get("ig")
    if not isinstance(profile, dict):
        result["status"] = "missing_profile_data"
        result["issues"] = "missing_ig_object"
        return result

    result["status"] = "ok"
    fields = (
        "username", "full_name", "is_private", "is_verified",
        "follower_count", "media_count", "following_count", "biography",
    )
    for field in fields:
        value = profile.get(field)
        if value is not None:
            result["returned_username" if field == "username" else field] = str(value)

    issues: List[str] = []
    private = profile.get("is_private")
    if private is True:
        issues.append("private_profile")

    followers = profile.get("follower_count")
    if isinstance(followers, int):
        minimum = row.get("min_followers", "").strip()
        maximum = row.get("max_followers", "").strip()
        if minimum:
            try:
                if followers < int(minimum):
                    issues.append("below_min_followers")
            except ValueError:
                issues.append("invalid_min_followers_rule")
        if maximum:
            try:
                if followers > int(maximum):
                    issues.append("above_max_followers")
            except ValueError:
                issues.append("invalid_max_followers_rule")
    elif row.get("min_followers", "").strip() or row.get("max_followers", "").strip():
        issues.append("follower_count_unavailable")

    expected_verified = parse_bool(row.get("verified", ""))
    actual_verified = profile.get("is_verified")
    if expected_verified is not None and isinstance(actual_verified, bool):
        if actual_verified != expected_verified:
            issues.append("verified_flag_mismatch")
    elif row.get("verified", "").strip():
        issues.append("verified_value_unavailable_or_invalid")

    result["issues"] = ";".join(issues)
    return result


with open("profiles.csv", newline="", encoding="utf-8-sig") as source:
    rows = list(csv.DictReader(source))

output = [check_row(row) for row in rows]
fieldnames = list(output[0].keys()) if output else [
    "requested_username", "status", "returned_username", "full_name",
    "is_private", "is_verified", "follower_count", "media_count",
    "following_count", "biography", "issues",
]

with open("profile_check.csv", "w", newline="", encoding="utf-8") as destination:
    writer = csv.DictWriter(destination, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(output)

print(f"Rows processed: {len(output)}; report: profile_check.csv")
```

 

## How to read discrepancy rows

 

Run `python check_profiles.py`. In the `status` column, `ok` means the script received the expected profile object and was able to create a record. The `issues` column contains only checked rules, such as `private_profile` or `below_min_followers`. An empty column means the recorded criteria did not reveal a discrepancy; it does not confirm content quality or compliance with other parts of an agreement.

 

Compare `returned_username` with the original username, and pass `biography` and `full_name` to a responsible team member for a contextual review. The report also includes request errors, unexpected API statuses, and missing `ig` objects. These rows remain in the output and help distinguish a technical failure from a check result.

 

## How to run the check regularly

 

For a one-off check, simply run the script manually. For a recurring process, add it to a scheduler or CI workflow: load the latest list, make the requests, save the CSV as an artifact, and notify the team if the `issues` column contains any values. Do not print the key to logs; store it as a runtime environment secret.

 

If you check the same profiles frequently, you can pass `cache_timeout` as the number of seconds to cache a response. The documentation states that caching is disabled by default for Instagram; a value greater than zero enables it for the specified period. Add this parameter only if reusing a response within the chosen interval is acceptable.

 

Check only data and use cases you are authorized to access. Treat the result as a snapshot of a specific API response, record the run date in your own log, and review thresholds alongside the brief. For details on the endpoint, available fields, and integration options, see the [Instagram Scraper API](https://jsonscraper.com/services/ig-scraper-api) and the [official endpoint documentation](https://github.com/jsonscraper/instagram-api-python/blob/main/docs/endpoints.md).
