Apify (actors and Instagram scraping)¶
When a service runs Apify actors — for example to
validate Instagram profiles or collect public posts — raw httpx wrappers
often repeat four bugs: placing the API token in the query string
(?token=..., leaking it into logs and traces), interpolating actor_id
without guarding against path traversal, swallowing HTTP errors into [], and
duplicating Instagram URL/handle parsing across services.
The SDK ships the generic async ApifyClient, the ApifySettings mixin, the
typed ApifyRequestException, the InstagramApifyScraper adapter with pure
username/URL helpers, and FakeApifyClient for offline tests.
Installation
No extra required. The client builds on the SDK's HTTPClient over
httpx, which is included in the base package.
Scope of the integration
Actor input and output shapes follow the Apify REST API v2
(/v2/acts/{actorId}/run-sync-get-dataset-items) and were verified
offline with httpx.MockTransport — nothing was measured against a live
paid account.
Configure with ApifySettings¶
Use ApifySettings to read the token, base URL, timeout and kill-switch from
the environment and pass them straight into apify_http_client.
from tempest_fastapi_sdk.integrations.scraping.apify import (
ApifyClient,
apify_http_client,
)
from tempest_fastapi_sdk.settings import (
ApifySettings,
BaseAppSettings,
EnvironmentSettings,
)
class Settings(EnvironmentSettings, ApifySettings, BaseAppSettings):
"""Application settings with Apify credentials."""
def build_apify_client(settings: Settings) -> ApifyClient:
"""Build an Apify client authenticated via Bearer header."""
http = apify_http_client(**settings.apify_http_kwargs())
return ApifyClient(http)
| Variable | Default | Effect |
|---|---|---|
APIFY_ENABLED |
true |
Kill-switch; false skips the production check and adds "apify" to disabled_integrations() |
APIFY_API_TOKEN |
"" |
Personal token sent as Authorization: Bearer <token> (never in the query string) |
APIFY_BASE_URL |
https://api.apify.com/v2 |
Apify REST API v2 base URL |
APIFY_TIMEOUT |
120.0 |
Per-request timeout in seconds (must be > 0) |
With ENV=production and APIFY_ENABLED=true, an empty APIFY_API_TOKEN
refuses to boot. Set APIFY_ENABLED=false when deploying before the token is
provisioned.
Timeout and retries on synchronous actor runs
When retry_policy=None, apify_http_client defaults to
RetryPolicy(retry_on_read_timeout=False) so a ReadTimeout does not
re-launch the same actor run multiple times.
Run any actor with ApifyClient¶
Use ApifyClient.run_actor_sync_items to execute any Apify actor synchronously
and receive its default dataset items as list[dict[str, JsonValue]].
from pydantic import JsonValue
from tempest_fastapi_sdk.exceptions import ApifyRequestException
from tempest_fastapi_sdk.integrations.scraping.apify import (
ApifyClient,
apify_http_client,
)
async def fetch_actor_items(
api_token: str,
actor_id: str,
run_input: dict[str, JsonValue],
) -> list[dict[str, JsonValue]]:
"""Run an Apify actor synchronously and return dataset items."""
http = apify_http_client(api_token, timeout=90.0)
async with ApifyClient(http) as client:
try:
return await client.run_actor_sync_items(actor_id, run_input)
except ApifyRequestException as exc:
raise exc
actor_id accepts owner~actor, owner/actor (normalized to owner~actor
in /acts/{actor_id}/run-sync-get-dataset-items), or an opaque actor ID.
Values containing .., extra slashes, whitespace, ?, or # raise
ValueError before any HTTP call is made.
Transport errors, non-2xx statuses, invalid JSON, or non-list/non-object
payloads are never swallowed: the client raises ApifyRequestException (HTTP
502, code APIFY_REQUEST_FAILED, translated in pt-BR and en-US),
preserving upstream_status, actor_id, and upstream_detail.
Pure Instagram helpers¶
Use extract_instagram_username and instagram_profile_url to normalize
user-supplied handles and URLs offline.
from tempest_fastapi_sdk.integrations.scraping.apify import (
extract_instagram_username,
instagram_profile_url,
)
def normalize_lead_instagram(raw_value: str) -> str | None:
"""Normalize an Instagram handle or URL into a canonical profile URL."""
username: str | None = extract_instagram_username(raw_value)
if username is None:
return None
return instagram_profile_url(username)
extract_instagram_username accepts instagram.com/..., instagr.am/...,
@handle, plain handles, or short text containing an Instagram URL, lowercases
the username, and rejects reserved Instagram routes (p, reel, reels,
stories, explore, accounts, direct, tv, about, legal, privacy,
terms, oauth, api, graphql, and similar), emails, non-Instagram hosts,
and disallowed characters.
Scrape posts and validate profiles with InstagramApifyScraper¶
Use InstagramApifyScraper to map apify~instagram-scraper and
apify~instagram-profile-scraper outputs onto InstagramPostSchema and
InstagramProfileSchema.
from tempest_fastapi_sdk.integrations.scraping.apify import (
ApifyClient,
InstagramApifyScraper,
InstagramPostSchema,
InstagramProfileSchema,
apify_http_client,
)
async def inspect_instagram_account(
api_token: str,
handle: str,
) -> tuple[InstagramProfileSchema, list[InstagramPostSchema]]:
"""Validate an Instagram profile and fetch up to 12 recent posts."""
http = apify_http_client(api_token)
async with ApifyClient(http) as client:
scraper = InstagramApifyScraper(client)
profile: InstagramProfileSchema = await scraper.validate_profile(handle)
if not profile.exists or profile.is_private:
return profile, []
posts: list[InstagramPostSchema] = await scraper.scrape_profile_posts(
profile.username,
max_posts=12,
)
return profile, posts
scrape_profile_postssendsdirectUrls,resultsType="posts", andresultsLimit=max_posts, normalizes camelCase/snake_case keys, parses ISO-8601 and Unix timestamps into UTC, and turns negative hidden-like sentinels (-1) intoNone. An empty dataset returns[].validate_profilesends{"usernames": [username]}, setsexists=Falsewhen the dataset is empty or contains only an error record (populatingerrors), and preservesis_private,followers_count, andposts_count.- Custom actor IDs can be passed through
post_actor_id=andprofile_actor_id=.
Test offline with FakeApifyClient¶
Use FakeApifyClient (exported from tempest_fastapi_sdk.testing.fakes and
tempest_fastapi_sdk.testing) to queue per-actor responses, trigger failures,
and inspect recorded calls without hitting the network.
from tempest_fastapi_sdk.exceptions import ApifyRequestException
from tempest_fastapi_sdk.integrations.scraping.apify import (
DEFAULT_INSTAGRAM_POST_ACTOR_ID,
DEFAULT_INSTAGRAM_PROFILE_ACTOR_ID,
InstagramApifyScraper,
)
from tempest_fastapi_sdk.testing.fakes import FakeApifyClient
async def run_offline_check() -> int:
"""Exercise InstagramApifyScraper with no token and no network."""
fake = FakeApifyClient()
fake.set_actor_items(
DEFAULT_INSTAGRAM_PROFILE_ACTOR_ID,
[
{
"username": "padaria.central",
"private": False,
"followersCount": 2400,
"postsCount": 55,
}
],
)
fake.enqueue_items(
[
{
"id": "1001",
"shortCode": "CxYz111",
"caption": "Fresh batch at 4pm",
"displayUrl": "https://cdn.example.com/1.jpg",
"timestamp": "2026-05-10T16:00:00Z",
"likesCount": 90,
"commentsCount": 8,
}
],
actor_id=DEFAULT_INSTAGRAM_POST_ACTOR_ID,
)
scraper = InstagramApifyScraper(fake)
profile = await scraper.validate_profile("@Padaria.Central")
posts = await scraper.scrape_profile_posts(profile.username, max_posts=5)
fake.fail_next(
ApifyRequestException(
upstream_status=429,
actor_id=DEFAULT_INSTAGRAM_POST_ACTOR_ID,
detail="rate-limit",
)
)
return len(posts)
See every exported symbol in the
integrations.scraping.apify API reference.
Recap¶
ApifySettingsmodelsAPIFY_ENABLED,APIFY_API_TOKEN,APIFY_BASE_URL, andAPIFY_TIMEOUT, with production validation andapify_http_kwargs().apify_http_clientauthenticates strictly viaAuthorization: Bearerand never in the query string.ApifyClient.run_actor_sync_itemsblocks path traversal inactor_idand raisesApifyRequestException(502,APIFY_REQUEST_FAILED) on HTTP, transport, or payload errors.extract_instagram_username,instagram_profile_url, andInstagramApifyScrapernormalize Instagram handles, profiles, and posts into Pydantic schemas.FakeApifyClientstands in forApifyClientin offline tests with queued responses, configurable errors, and call recording.