Apify Client for Elixir

Copy Markdown View Source

An Elixir client for the Apify platform and its API.

Apify is a web scraping and automation platform that lets you turn websites into APIs. This library covers the whole Apify API: Actors, runs, builds, tasks, datasets, key-value stores, request queues, schedules, webhooks, the Store and your account.

About this library

  • Generated from the API description. The ApifyClient.API modules are generated from Apify's OpenAPI description, so they cover every endpoint and are regenerated as the API changes. The modules for common tasks (ApifyClient.Actors, ApifyClient.Runs, …) are hand-written on top of them.
  • Tested offline and against the real API. The test suite runs against stubbed responses; before a release, the scripts in examples/smoke/ check the client against a real Apify account and clean up after themselves.
  • Built with AI assistance. Large parts were written with Claude Code and reviewed and tested as described above.
  • Unofficial. This is a community library, not maintained by Apify. For the official clients, see the Apify documentation.

Installation

Add apify_client to your list of dependencies in mix.exs:

def deps do
  [
    {:apify_client, "~> 1.0"}
  ]
end

Quick start

Sign up for a free Apify account and get your API token from the Apify Console. Then run an Actor and read its results:

config = ApifyClient.Config.new(token: "apify_api_...")

{:ok, run} =
  ApifyClient.Actors.call(
    "apify/web-scraper",
    %{"startUrls" => [%{"url" => "https://example.com"}], "maxPagesPerCrawl" => 10},
    config: config
  )

if ApifyClient.Runs.succeeded?(run) do
  {:ok, items} = ApifyClient.Datasets.list_items(run.default_dataset_id, config: config)
end

Without a token (config: or token:), requests are sent unauthenticated, which works only for public endpoints such as the Store. The client never reads the token from the environment; pass it explicitly, for example token: System.fetch_env!("APIFY_TOKEN").

run is an %ApifyClient.Schemas.Run{} struct with snake_case fields (run.status, run.started_at as a DateTime, ...).

Two layers

Common tasks have hand-written modules:

ModuleFunctions
ApifyClient.Actorsstart/3, call/3 (start and wait), build/3, get/2, safe_id/1
ApifyClient.Tasksstart/3, call/3 (start and wait), get/2, safe_id/1
ApifyClient.Runsget/2, wait_for_finish/2, abort/2, finished?/1, succeeded?/1
ApifyClient.Buildsget/2, wait_for_finish/2, abort/2, finished?/1, succeeded?/1
ApifyClient.Datasetslist_items/2, stream_items/2, push_items/3
ApifyClient.KeyValueStoresget_record/3, put_record/4, delete_record/3, record_exists?/3, list_keys/2, stream_keys/2
ApifyClient.Logsget/2, stream/2
ApifyClient.Paginationstream/2: every item of any paginated list endpoint

The whole API is under ApifyClient.API, generated from Apify's OpenAPI description. There is one module per resource, and functions are named after the URL path:

RequestFunction
GET /v2/actor-runs/{runId}ApifyClient.API.Runs.get(run_id, opts)
POST /v2/actor-runs/{runId}/abortApifyClient.API.Runs.abort(run_id, opts)
GET /v2/actors/{actorId}/runsApifyClient.API.Actors.Runs.list(actor_id, opts)
POST /v2/actor-tasks/{actorTaskId}/runsApifyClient.API.Tasks.Runs.create(task_id, input, opts)
POST /v2/webhooksApifyClient.API.Webhooks.create(webhook, opts)
GET /v2/storeApifyClient.API.Store.list(opts)
GET /v2/users/meApifyClient.API.Users.Me.get(opts)

Query parameters are snake_case options (max_items: 10 is sent as maxItems=10). Responses are decoded into the structs in ApifyClient.Schemas.

Configuration

Every call takes its connection settings as options: a %ApifyClient.Config{} as config:, or individual settings, which override the ones in config::

config = ApifyClient.Config.new(
  token: "apify_api_...",                 # default: none (unauthenticated requests)
  base_url: "https://api.apify.com",      # default
  timeout_ms: 360_000,                    # receive timeout per request (default)
  max_retries: 8,                         # default
  min_delay_between_retries_ms: 500,      # default
  json_library: ApifyClient.JSON.Native   # default
)

ApifyClient.Actors.start("apify/web-scraper", input, config: config, max_retries: 2)

Following the Elixir library guidelines, the client does not read these settings from the application environment. Keep them in your own application's configuration and build the Config there:

# config/runtime.exs
config :my_app, :apify_token, System.fetch_env!("APIFY_TOKEN")

# lib/my_app/apify.ex
defmodule MyApp.Apify do
  def config, do: ApifyClient.Config.new(token: Application.fetch_env!(:my_app, :apify_token))
end

ApifyClient.Runs.get(run_id, config: MyApp.Apify.config())

The application environment is only used to swap components: the JSON library (config :apify_client, :json_library, ...) and, in tests, a Req.Test plug (config :apify_client, :req_options, ...).

Rate limits (429), server errors (5xx) and network errors are retried with randomized exponential backoff, as the Apify API documentation recommends.

Responses and errors

  • The API's {"data": ...} envelope is removed, and JSON is decoded into ApifyClient.Schemas structs.
  • Untyped JSON (Actor input and output, key-value records, dataset items) comes back as decoded maps with string keys.
  • Non-JSON responses (logs, CSV/XLSX dataset items, files in key-value stores) come back as binaries.
  • Calls without a response body (deletes, HEAD) return :ok.
  • Failures are {:error, %ApifyClient.Error{}}:
case ApifyClient.Actors.get("apify/web-scraper") do
  {:ok, actor} ->
    actor.name

  {:error, %ApifyClient.Error{type: :not_found_error}} ->
    nil

  {:error, %ApifyClient.Error{type: :authentication_error}} ->
    raise "check your API token"

  {:error, %ApifyClient.Error{} = error} ->
    # error.details has :status_code, :error_type (e.g. "record-not-found") and :body
    raise error
end

Request bodies

Pass schema structs (snake_case fields) or plain maps. Plain maps are sent unchanged, so they use the API's own camelCase names; this is also how Actor input is passed:

ApifyClient.API.Datasets.update(dataset_id, %ApifyClient.Schemas.UpdateDatasetRequest{name: "results"})
ApifyClient.API.Datasets.update(dataset_id, %{"name" => "results"})

Key-value records and Actor input also accept binaries; set :content_type for them:

:ok = ApifyClient.KeyValueStores.put_record(store_id, "screenshot.png", png, content_type: "image/png")

Streaming

Dataset items are fetched page by page as the stream is consumed:

ApifyClient.Datasets.stream_items(dataset_id, clean: true)
|> Stream.filter(& &1["price"])
|> Stream.chunk_every(500)
|> Enum.each(&MyApp.Products.insert_batch/1)

Any paginated list endpoint can be streamed the same way:

ApifyClient.Pagination.stream(&ApifyClient.API.Actors.Runs.list("apify~web-scraper", &1), desc: true)
|> Stream.filter(&(&1.status == "FAILED"))
|> Enum.take(10)

Logs of running Actors can be followed:

{:ok, stream} = ApifyClient.Logs.stream(run.id)
Enum.each(stream, &IO.write/1)

Testing your application

Route the client to a Req.Test stub:

# config/test.exs
config :apify_client, req_options: [plug: {Req.Test, MyApp.ApifyStub}]

# in a test
Req.Test.stub(MyApp.ApifyStub, fn conn ->
  Req.Test.json(conn, %{"data" => %{"id" => "run-1", "status" => "SUCCEEDED"}})
end)

Individual calls also take req_options:.

JSON library

JSON goes through the ApifyClient.JSON behaviour. The default adapter, ApifyClient.JSON.Native, uses Elixir's built-in JSON module. To use Jason, add it to your dependencies and configure:

config :apify_client, :json_library, ApifyClient.JSON.Jason

Telemetry

Every request emits [:apify_client, :request, :start | :stop | :exception] events with bounded metadata (method, top-level resource, status, error type). See ApifyClient.Telemetry.

Requirements

  • Elixir 1.18+ (for the built-in JSON module)
  • An Apify account and API token (sign up free)

Development

The modules in lib/apify_client/api/ and lib/apify_client/schemas/ are generated; don't edit them by hand.

mix apify.spec.update   # download the latest OpenAPI description to openapi/apify.json
mix apify.gen           # regenerate lib/apify_client/{api,schemas}

The generator plugins live in dev/apify_client/generator/. CI checks that the generated code matches the committed description.

examples/smoke/ has scripts that check the client against a real Apify account and clean up after themselves; see its README.

Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Add tests for new functionality
  4. Run mix test, mix credo --strict and mix dialyzer
  5. Submit a pull request

License

Apache 2.0 - see LICENSE file.