Ir para o conteúdo

tempest_fastapi_sdk.integrations.scraping.apify

Apify REST API v2: cliente assíncrono para actors síncronos, adapter e helpers de scraping de Instagram.

« Integrações e pagamentos


client

Async REST API v2 client for Apify synchronous actor runs.

Calls POST /acts/{actorId}/run-sync-get-dataset-items with Authorization: Bearer <token> (never placing the token in the URL query string), strictly validates actor_id against path traversal, and surfaces HTTP, transport and payload errors as :class:~tempest_fastapi_sdk.exceptions.ApifyRequestException instead of silently returning an empty list.

APIFY_BASE_URL module-attribute

APIFY_BASE_URL: str = 'https://api.apify.com/v2'

Default base URL of the Apify REST API v2.

ApifyClientProtocol

Bases: Protocol

Async interface implemented by :class:ApifyClient and FakeApifyClient.

run_actor_sync_items async

run_actor_sync_items(
    actor_id: str, run_input: Mapping[str, JsonValue], *, timeout: float | None = None
) -> list[dict[str, JsonValue]]

Run an Apify actor synchronously and return its dataset items.

Parameters:

Name Type Description Default
actor_id str

Apify actor ID or owner~actor / owner/actor.

required
run_input Mapping[str, JsonValue]

JSON body sent as actor input.

required
timeout float | None

Optional per-call timeout override in seconds.

None

Returns:

Type Description
list[dict[str, JsonValue]]

list[dict[str, JsonValue]]: Dataset items returned by the actor run.

ApifyClient

ApifyClient(http: HTTPClient)

Generic async client for running Apify actors synchronously.

Example

http = apify_http_client("apify_api_secret") client = ApifyClient(http) items = await client.run_actor_sync_items( ... "apify~instagram-profile-scraper", ... {"usernames": ["instagram"]}, ... )

Wrap an :class:~tempest_fastapi_sdk.utils.HTTPClient aimed at Apify.

Parameters:

Name Type Description Default
http HTTPClient

Configured client from :func:apify_http_client.

required

aclose async

aclose() -> None

Close the underlying HTTP connection pool.

run_actor_sync_items async

run_actor_sync_items(
    actor_id: str, run_input: Mapping[str, JsonValue], *, timeout: float | None = None
) -> list[dict[str, JsonValue]]

Run an actor synchronously and return its dataset items.

Sends POST /acts/{encoded_actor_id}/run-sync-get-dataset-items with run_input serialized as JSON.

Parameters:

Name Type Description Default
actor_id str

Apify actor ID, owner~actor or owner/actor.

required
run_input Mapping[str, JsonValue]

JSON input payload for the actor.

required
timeout float | None

Optional per-call timeout override in seconds.

None

Returns:

Type Description
list[dict[str, JsonValue]]

list[dict[str, JsonValue]]: The list of JSON objects produced by

list[dict[str, JsonValue]]

the actor's default dataset.

Raises:

Type Description
ValueError

When actor_id is invalid or timeout is not positive.

ApifyRequestException

When the HTTP request fails, returns a non-2xx status, or returns a payload that is not a JSON list of objects.

normalize_actor_id

normalize_actor_id(actor_id: str) -> str

Validate and normalize an Apify actor identifier for a single URL path segment.

Accepts either an opaque actor ID ("aYG0l9s7dbB7j3gbS") or a two-part owner~actor / owner/actor slug. A single / separator is normalized to ~ per the Apify REST API v2 path convention.

Parameters:

Name Type Description Default
actor_id str

Raw actor identifier provided by the caller.

required

Returns:

Name Type Description
str str

Normalized actor identifier safe for interpolation into

str

/acts/{actor_id}/run-sync-get-dataset-items.

Raises:

Type Description
ValueError

When actor_id is empty, contains whitespace, path traversal (..), extra slashes, query/fragment characters, or any disallowed character.

apify_http_client

apify_http_client(
    api_token: str,
    *,
    base_url: str = APIFY_BASE_URL,
    timeout: float = 120.0,
    retry_policy: RetryPolicy | None = None,
    transport: AsyncBaseTransport | None = None,
) -> HTTPClient

Build the :class:~tempest_fastapi_sdk.utils.HTTPClient for Apify v2.

Authenticates strictly through the Authorization: Bearer <token> header and never attaches ?token=... to the URL. When retry_policy is None, retries on ReadTimeout are disabled by default so a slow synchronous actor run is not accidentally launched multiple times.

Parameters:

Name Type Description Default
api_token str

Apify personal API token.

required
base_url str

Apify REST API v2 base URL.

APIFY_BASE_URL
timeout float

Per-request timeout in seconds.

120.0
retry_policy RetryPolicy | None

Custom retry policy, or None to use RetryPolicy(retry_on_read_timeout=False).

None
transport AsyncBaseTransport | None

Optional transport override (for example httpx.MockTransport in tests).

None

Returns:

Name Type Description
HTTPClient HTTPClient

Configured async HTTP client for :class:ApifyClient.

Raises:

Type Description
ValueError

When api_token or base_url is empty or blank, or when timeout is not positive.

instagram

Instagram scraping adapter and pure username/URL helpers built on Apify.

Provides:

  • Pure helpers (:func:extract_instagram_username and :func:instagram_profile_url) that normalize handles and Instagram URLs while rejecting reserved routes and invalid characters.
  • Typed Pydantic schemas (:class:InstagramPostSchema and :class:InstagramProfileSchema).
  • :class:InstagramApifyScraper, which delegates actor execution to any :class:~tempest_fastapi_sdk.integrations.scraping.apify.ApifyClientProtocol (including :class:ApifyClient and FakeApifyClient).

DEFAULT_INSTAGRAM_POST_ACTOR_ID module-attribute

DEFAULT_INSTAGRAM_POST_ACTOR_ID: str = 'apify~instagram-scraper'

Default Apify actor ID used by :meth:InstagramApifyScraper.scrape_profile_posts.

DEFAULT_INSTAGRAM_PROFILE_ACTOR_ID module-attribute

DEFAULT_INSTAGRAM_PROFILE_ACTOR_ID: str = 'apify~instagram-profile-scraper'

Default Apify actor ID used by :meth:InstagramApifyScraper.validate_profile.

INSTAGRAM_RESERVED_PATHS module-attribute

INSTAGRAM_RESERVED_PATHS: frozenset[str] = frozenset(
    {
        "about",
        "accounts",
        "api",
        "ar",
        "blog",
        "call",
        "challenge",
        "channel",
        "create",
        "developer",
        "developers",
        "direct",
        "directory",
        "download",
        "emails",
        "explore",
        "graphql",
        "help",
        "jobs",
        "legal",
        "lite",
        "locations",
        "login",
        "logout",
        "nametag",
        "notifications",
        "oauth",
        "p",
        "press",
        "privacy",
        "reel",
        "reels",
        "safety",
        "security",
        "session",
        "settings",
        "shop",
        "shopping",
        "signup",
        "static",
        "store",
        "stories",
        "support",
        "tags",
        "terms",
        "tv",
        "web",
        "your_activity",
    }
)

Top-level Instagram URL path segments that do not identify a user profile.

InstagramPostSchema

Bases: BaseSchema

Normalized Instagram post scraped from an Apify actor dataset.

Attributes:

Name Type Description
post_id str

Stable identifier reported by Apify or Instagram.

shortcode str | None

Public post shortcode (the segment after /p/ or /reel/).

caption str | None

Post caption text, when present.

media_url str | None

Primary image or video URL reported by the actor.

posted_at datetime | None

UTC publication timestamp, when present.

post_url str | None

Canonical post URL.

likes_count int | None

Non-negative like count, or None when unavailable or hidden (Apify reports -1 for hidden counts).

comments_count int | None

Non-negative comment count, or None when unavailable.

InstagramProfileSchema

Bases: BaseSchema

Normalized Instagram profile validation result from Apify.

Attributes:

Name Type Description
username str

Normalized lowercase Instagram username.

exists bool

Whether the profile exists according to Apify.

is_private bool

Whether the profile is private.

followers_count int | None

Follower count when reported.

posts_count int | None

Post count when reported.

errors list[str]

Upstream actor-level error codes or descriptions returned in dataset items (empty on a clean hit).

InstagramApifyScraper

InstagramApifyScraper(
    client: ApifyClientProtocol,
    *,
    post_actor_id: str = DEFAULT_INSTAGRAM_POST_ACTOR_ID,
    profile_actor_id: str = DEFAULT_INSTAGRAM_PROFILE_ACTOR_ID,
)

High-level Instagram scraper built over an Apify client.

Translates Instagram usernames into Apify actor inputs and parses dataset items into :class:InstagramPostSchema and :class:InstagramProfileSchema. HTTP and transport failures from the underlying client are never swallowed and propagate as :class:~tempest_fastapi_sdk.exceptions.ApifyRequestException.

Example

client = ApifyClient(apify_http_client("apify_api_secret")) scraper = InstagramApifyScraper(client) posts = await scraper.scrape_profile_posts("@instagram", max_posts=5)

Initialize the Instagram scraper.

Parameters:

Name Type Description Default
client ApifyClientProtocol

Real :class:ApifyClient or FakeApifyClient.

required
post_actor_id str

Apify actor used by :meth:scrape_profile_posts.

DEFAULT_INSTAGRAM_POST_ACTOR_ID
profile_actor_id str

Apify actor used by :meth:validate_profile.

DEFAULT_INSTAGRAM_PROFILE_ACTOR_ID

Raises:

Type Description
ValueError

When either configured actor ID fails validation.

scrape_profile_posts async

scrape_profile_posts(
    username: str, *, max_posts: int = 12
) -> list[InstagramPostSchema]

Scrape recent posts from an Instagram profile.

Parameters:

Name Type Description Default
username str

Instagram handle or profile URL.

required
max_posts int

Maximum number of posts to request and return.

12

Returns:

Type Description
list[InstagramPostSchema]

list[InstagramPostSchema]: Parsed posts, or [] when the actor

list[InstagramPostSchema]

returns no post items.

Raises:

Type Description
ValueError

When username is invalid or max_posts is not positive.

ApifyRequestException

Propagated when the underlying Apify request fails.

validate_profile async

validate_profile(username: str) -> InstagramProfileSchema

Validate whether an Instagram profile exists and inspect its metadata.

Parameters:

Name Type Description Default
username str

Instagram handle or profile URL.

required

Returns:

Name Type Description
InstagramProfileSchema InstagramProfileSchema

Normalized profile existence, privacy,

InstagramProfileSchema

counts and any actor-reported errors.

Raises:

Type Description
ValueError

When username is invalid.

ApifyRequestException

Propagated when the underlying Apify request fails.

extract_instagram_username

extract_instagram_username(text: str) -> str | None

Extract and normalize an Instagram username from a URL, @handle or handle.

Accepts https://www.instagram.com/<handle>/, instagr.am/<handle>, schemeless instagram.com/<handle>, @handle, plain handle, or short text containing an Instagram profile URL. Rejects generic Instagram routes (such as p, reel, reels, stories, explore, accounts, direct, tv), non-Instagram URLs, emails, consecutive dots, leading/trailing dots, and characters outside [a-z0-9._].

Parameters:

Name Type Description Default
text str

Raw user-supplied handle, URL, or text snippet.

required

Returns:

Type Description
str | None

str | None: Normalized lowercase username (1 to 30 characters), or

str | None

None when no valid Instagram username can be extracted.

instagram_profile_url

instagram_profile_url(username: str) -> str

Build the canonical HTTPS profile URL for an Instagram username.

Normalizes username via :func:extract_instagram_username so inputs like "@MyShop" or "https://instagram.com/MyShop/" produce the canonical URL "https://www.instagram.com/myshop/".

Parameters:

Name Type Description Default
username str

Instagram handle or profile URL.

required

Returns:

Name Type Description
str str

Canonical profile URL https://www.instagram.com/{username}/.

Raises:

Type Description
ValueError

When username cannot be normalized to a valid Instagram username.