# fal api Source: https://fal.ai/docs/api-reference/cli/api Call any model on fal directly from the command line. Useful for quick testing without writing code. ## Usage ```bash theme={null} fal api [key=value ...] ``` **Arguments:** | Argument | Description | | ---------- | ---------------------------------------------------------------- | | `model_id` | The model endpoint to call (e.g., `fal-ai/flux/schnell`) | | `params` | Key-value pairs for the request body (e.g., `prompt="a sunset"`) | ## Examples **Generate an image:** ```bash theme={null} fal api fal-ai/flux/schnell prompt="a cat wearing sunglasses" ``` The CLI shows real-time status updates (queued, in progress) and logs while the request is processing, then prints the result. **Nested parameters:** Use bracket notation for nested values: ```bash theme={null} fal api fal-ai/flux/schnell prompt="a sunset" image_size[width]:=1280 image_size[height]:=720 ``` Use `:=` for non-string values (numbers, booleans): ```bash theme={null} fal api fal-ai/flux/schnell prompt="a sunset" num_images:=4 seed:=42 ``` **Streaming endpoints:** If the model ID ends with `/stream`, the CLI streams output as it's generated: ```bash theme={null} fal api fal-ai/any-llm/stream prompt="What is the meaning of life?" model=google/gemini-flash-1.5 ``` ## How It Works * For regular endpoints: submits via the queue, polls for status with live log display, then prints the result * For `/stream` endpoints: connects via streaming and prints output as it arrives * Uses your configured `FAL_KEY` for authentication # fal apps delete Source: https://fal.ai/docs/api-reference/cli/apps/delete ```bash theme={null} Usage: fal apps delete [-h] [--debug] [--pdb] [--cprofile] [--env ENV] app_name Delete application. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Examples: fal apps delete my-app fal apps delete my-app --env staging ``` # fal apps delete-rev Source: https://fal.ai/docs/api-reference/cli/apps/delete-rev ```bash theme={null} Usage: fal apps delete-rev [-h] [--debug] [--pdb] [--cprofile] app_rev Delete application revision. Positional Arguments: app_rev Application revision. Options: -h, --help show this help message and exit ``` # fal apps list Source: https://fal.ai/docs/api-reference/cli/apps/list ```bash theme={null} Usage: fal apps list [-h] [--debug] [--pdb] [--cprofile] [--sort-by-runners] [--filter FILTER] [--env ENV] [--regions REGIONS [REGIONS ...]] [--output {pretty,json}] [--json] List applications. Options: -h, --help show this help message and exit --sort-by-runners Sort by number of runners ascending. --filter FILTER Filter applications by alias contents. --env ENV Target environment (defaults to main). --regions REGIONS [REGIONS ...] Valid regions (pass several items to filter on multiple). Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal apps list fal apps list --env staging fal apps list --filter myapp --sort-by-runners fal apps list --json ``` # fal apps list-rev Source: https://fal.ai/docs/api-reference/cli/apps/list-rev ```bash theme={null} Usage: fal apps list-rev [-h] [--debug] [--pdb] [--cprofile] [--env ENV] [app_name] List application revisions. Positional Arguments: app_name Application name (optional). Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). ``` # fal apps rollout Source: https://fal.ai/docs/api-reference/cli/apps/rollout ```bash theme={null} Usage: fal apps rollout [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] [--force] [--env ENV] app_name Rollout application by restarting all active runners. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. --force Force rollout by killing runners immediately instead of gracefully stopping them. --env ENV Target environment (defaults to main). Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` ## When to Use Use `fal apps rollout` when you need to replace all runners for an application without redeploying: * **Environment variable changes**: Force runners to pick up updated secrets or environment variables * **Bad state recovery**: Replace runners that may be in an unhealthy state * **Memory cleanup**: Force garbage collection and memory cleanup across all runners * **Configuration updates**: Apply changes that require a fresh runner * **Machine type changes**: Move existing runners onto a machine type you changed with `fal apps scale` -- see [Changing Machine Types](/docs/documentation/deployment/machine-types#rolling-out-existing-runners) ## Graceful vs Force Rollout ### Graceful Rollout (Default) ```bash theme={null} fal apps rollout myapp ``` Brings up replacement runners before draining the existing ones, so requests are not interrupted. This is the recommended approach for most situations. **How it works:** 1. Identifies all active runners for the application 2. Marks each one for replacement -- they keep serving requests in the meantime 3. Starts replacement runners on the application's current configuration 4. As each new runner finishes starting up and joins the application, one marked runner stops accepting new requests and drains the ones it is still processing Replacements are started in parallel rather than one at a time, so while the rollout is in progress the application can run close to double its usual runner count -- and is billed for both sets. If your account's GPU limits are already fully consumed, replacements wait until capacity frees up and the marked runners keep serving in the meantime. ### Force Rollout ```bash theme={null} fal apps rollout myapp --force ``` Immediately kills all active runners without waiting for current requests to complete. Use this when runners are unresponsive or when you need an immediate restart. **How it works:** 1. Identifies all active runners for the application 2. Immediately terminates all runners 3. New runners are automatically started by the auto-scaling system Force rollout will terminate in-flight requests, potentially causing errors for active users. Use the graceful rollout (without `--force`) unless absolutely necessary. ## Examples ### Rollout after updating a secret ```bash theme={null} # Update a secret fal secrets set MY_API_KEY new_value # Gracefully rollout to pick up the new secret fal apps rollout myapp ``` ### Rollout in a specific environment ```bash theme={null} # Update a secret in staging fal secrets set MY_API_KEY staging_value --env staging # Rollout the staging environment fal apps rollout myapp --env staging ``` ### Force rollout to recover from frozen runners ```bash theme={null} # Check runners status fal apps runners myapp # Force immediate restart if runners are unresponsive fal apps rollout myapp --force ``` ## Difference from Redeployment `fal apps rollout` is different from `fal deploy`: * **`fal apps rollout`**: Replaces existing runners without creating a new revision, so they come up on the app's current configuration. Useful for applying environment or machine-type changes and recovering from bad states. * **`fal deploy`**: Creates a new revision of your application with updated code and configuration. Use this when you've made code changes. ## See Also * [fal deploy](/docs/serverless/cli/deploy) - Deploy a new revision of your application * [fal apps scale](/docs/serverless/cli/apps/scale) - Adjust scaling parameters * [fal apps runners](/docs/serverless/cli/apps/runners) - View active runners for an application # fal apps runners Source: https://fal.ai/docs/api-reference/cli/apps/runners ```bash theme={null} Usage: fal apps runners [-h] [--team TEAM] [--env ENV] [--since SINCE] [--state {all,idle,running,pending,setup,crash_backoff,terminated} [...]] [--output {pretty,json}] [--json] app_name List application runners. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. --env ENV Target environment (defaults to main). --since SINCE Show terminated runners since the given time. Accepts 'now', relative like '30m', '1h', '1d', or an ISO timestamp. Max 24 hours. --state {all,idle,running,pending,setup,crash_backoff,terminated} [{all,idle,running,pending,setup,crash_backoff,terminated} ...] Filter by runner state(s). Choose one or more, or 'all' (default). Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal apps runners my-app fal apps runners my-app --env staging ``` The runner table displays the following columns: * **Alias** -- Application name * **Machine Type** -- Hardware type (e.g. `GPU-A100`, `GPU-H100`) * **Runner ID** -- Unique runner identifier * **In Flight Requests** -- Number of active requests * **Expires In** -- Time until runner expires * **Uptime** -- How long the runner has been running * **Revision** -- Application revision * **State** -- Current runner state # fal apps scale Source: https://fal.ai/docs/api-reference/cli/apps/scale ```bash theme={null} Usage: fal apps scale [-h] [--debug] [--pdb] [--cprofile] [--keep-alive KEEP_ALIVE] [--max-multiplexing MAX_MULTIPLEXING] [--max-concurrency MAX_CONCURRENCY] [--min-concurrency MIN_CONCURRENCY] [--concurrency-buffer CONCURRENCY_BUFFER] [--concurrency-buffer-perc CONCURRENCY_BUFFER_PERC] [--scaling-delay SCALING_DELAY] [--request-timeout REQUEST_TIMEOUT] [--startup-timeout STARTUP_TIMEOUT] [--machine-types MACHINE_TYPES [MACHINE_TYPES ...]] [--regions REGIONS [REGIONS ...]] [--env ENV] app_name Scale application. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --keep-alive KEEP_ALIVE Keep alive (seconds). --max-multiplexing MAX_MULTIPLEXING Maximum multiplexing --max-concurrency MAX_CONCURRENCY Maximum concurrency. --min-concurrency MIN_CONCURRENCY Minimum concurrency --concurrency-buffer CONCURRENCY_BUFFER Concurrency buffer (minimum extra capacity). --concurrency-buffer-perc CONCURRENCY_BUFFER_PERC Concurrency buffer expressed as a percentage. --scaling-delay SCALING_DELAY Scaling delay (seconds). --request-timeout REQUEST_TIMEOUT Request timeout (seconds). If a request takes longer, it is aborted and the runner gracefully stopped as it could be in a bad state. --startup-timeout STARTUP_TIMEOUT Startup timeout (seconds). --machine-types MACHINE_TYPES [MACHINE_TYPES ...] Machine types (pass several items to set multiple). --regions REGIONS [REGIONS ...] Valid regions (pass several items to set multiple). --env ENV Target environment (defaults to main). ``` **Note:** Redeploying the application, by default, will not reset these settings, except for the code-specific settings. See [Code-Specific Settings (Reset on Deploy)](/docs/serverless/deployment-operations/scale-your-application#code-specific-settings-reset-on-deploy) for details. # fal apps set-rev Source: https://fal.ai/docs/api-reference/cli/apps/set-rev ```bash theme={null} Usage: fal apps set-rev [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] [--auth {public,private,shared}] [--strategy {recreate,rolling}] [--env ENV] app_name app_rev Set application to a particular revision. Positional Arguments: app_name Application name. app_rev Application revision. Options: -h, --help show this help message and exit --team TEAM The team to use. --auth {public,private,shared} Application authentication mode. --strategy {recreate,rolling} Deployment strategy. --env ENV Target environment (defaults to main). Can also be set via FAL_ENV environment variable. Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` # fal auth Source: https://fal.ai/docs/api-reference/cli/auth ```bash theme={null} fal auth [-h] [--debug] [--pdb] [--cprofile] command ... Authenticate with fal. Options: -h, --help show this help message and exit Commands: command login Log in a user. logout Log out the currently logged-in user. whoami Show the currently authenticated user. ``` ## Login ```bash theme={null} Usage: fal auth login [-h] [--debug] [--pdb] [--cprofile] [--connection CONNECTION] [--no-browser] Log in a user. Options: -h, --help show this help message and exit --connection CONNECTION Auth connection (e.g. github, google, or an SSO domain). Skips the interactive prompt. --no-browser Don't attempt to open a browser. Just print the URL to visit. ``` When `--connection` is omitted, the CLI prompts you to choose between GitHub, Google, or your enterprise SSO domain. The previously used choice is remembered and offered as the default on subsequent logins. ## Logout ```bash theme={null} Usage: fal auth logout [-h] [--debug] [--pdb] [--cprofile] [--no-browser] Log out the currently logged-in user. Options: -h, --help show this help message and exit --no-browser Don't attempt to open a browser. Just print the URL to visit. ``` ## Whoami ```bash theme={null} Usage: fal auth whoami [-h] [--debug] [--pdb] [--cprofile] Show the currently authenticated user. Options: -h, --help show this help message and exit Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` # fal create Source: https://fal.ai/docs/api-reference/cli/create ```bash theme={null} Usage: fal create [-h] [--debug] [--pdb] [--cprofile] project_type Create fal applications. Positional Arguments: project_type Type of project to create. Options: -h, --help show this help message and exit ``` # fal deploy Source: https://fal.ai/docs/api-reference/cli/deploy Before deploying, validate your app with [`fal run`](/docs/api-reference/cli/run). It boots your app on a temporary worker — running `setup()` and your endpoints just like production — so import and model-loading errors surface locally instead of as a production crashloop. On a first deploy or after a failed deploy, the CLI reminds you to do this. See [Development vs Production](/docs/documentation/deployment/deploy-to-production#development-vs-production). ```bash theme={null} Usage: fal deploy [-h] [--output {pretty,json}] [--json] [--team TEAM] [--app-name APP_NAME] [--auth AUTH] [--strategy {recreate,rolling}] [--no-scale] [--reset-scale] [--check] [--yes] [--message MESSAGE] [--annotation KEY=VALUE] [--no-cache] [--env ENV] [app_ref] Deploy a fal application. If no app reference is provided, the command will look for a pyproject.toml file with a [tool.fal.apps] section and deploy the application specified with the provided app name. Positional Arguments: app_ref Application reference. Either a file path or a file path and a function name separated by '::'. If no reference is provided, the command will look for a pyproject.toml file with a [tool.fal.apps] section and deploy the application specified with the provided app name. File path example: path/to/myfile.py::MyApp App name example: my-app (configure team in pyproject.toml) Options: -h, --help show this help message and exit --team TEAM The team to use. --app-name APP_NAME Application name to deploy with. --auth AUTH Application authentication mode (private, public, shared). --strategy {recreate,rolling} Deployment strategy. --no-scale Use the previous deployment of the application for scale settings. This is the default behavior. --reset-scale Use the application code for scale settings. --check Show a pre-deployment summary before deploying. Prompts for confirmation unless --yes is also set. --yes Skip interactive deploy confirmation prompts. When combined with --check, the summary is still shown. --message MESSAGE Freeform message to attach to this revision (e.g, 'add feature') --annotation KEY=VALUE Custom key=value pair to attach to this revision (e.g, GIT_SHA=1234567890). Can be repeated. Value must be a string. --no-cache Do not use the cache for the environment build. --env ENV Target environment (defaults to main). Can also be set via FAL_ENV environment variable. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal deploy fal deploy path/to/myfile.py fal deploy path/to/myfile.py::MyApp fal deploy path/to/myfile.py::MyApp --app-name myapp --auth public fal deploy path/to/myfile.py::MyApp --check fal deploy path/to/myfile.py::MyApp --check --yes fal deploy path/to/myfile.py::MyApp --env staging fal deploy my-app fal deploy my-app --message "a1b2c3d fix cold-start" fal deploy my-app --annotation DEPLOYER_ID=foo-123 --annotation GIT_SHA=1234567890 ``` # fal doctor Source: https://fal.ai/docs/api-reference/cli/doctor ```bash theme={null} Usage: fal doctor [-h] [--debug] [--pdb] [--cprofile] [--output {pretty,json}] [--json] fal version and misc environment information. Options: -h, --help show this help message and exit Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` Outputs the installed `fal` and `isolate` versions, the Python version and platform, and the configured `FAL_HOST` and the prefix of the active `FAL_KEY`. Useful when filing bug reports. # fal environments Source: https://fal.ai/docs/api-reference/cli/environments ```bash theme={null} Usage: fal environments [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal environments. Options: -h, --help show this help message and exit Commands: command list List environments. create Create an environment. delete Delete an environment. ``` The `environments` command also has an alias `envs` for convenience: ```bash theme={null} fal envs list ``` ## List ```bash theme={null} Usage: fal environments list [-h] [--debug] [--pdb] [--cprofile] [--output {pretty,json}] [--json] List environments. Options: -h, --help show this help message and exit Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal environments list fal envs list --output json ``` ## Create ```bash theme={null} Usage: fal environments create [-h] [--debug] [--pdb] [--cprofile] [--description DESCRIPTION] name Create an environment. Positional Arguments: name Environment name. Options: -h, --help show this help message and exit --description DESCRIPTION Environment description. Examples: fal environments create staging fal envs create dev --description "Development environment" ``` ## Delete ```bash theme={null} Usage: fal environments delete [-h] [--debug] [--pdb] [--cprofile] [--yes] name Delete an environment. Positional Arguments: name Environment name. Options: -h, --help show this help message and exit --yes Skip confirmation prompt. Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` Deleting an environment permanently removes all apps and secrets in that environment. You will be prompted to confirm by typing the environment name unless `--yes` is provided. ## Using Environments with Other Commands Once you've created environments, you can target them using the `--env` flag in other commands: ```bash theme={null} # Deploy to an environment fal deploy path/to/myapp.py::MyApp --env staging # Manage secrets per environment fal secrets set API_KEY=value --env staging fal secrets list --env staging # Manage apps per environment fal apps list --env staging fal apps scale my-app --min-concurrency 1 --env staging fal apps runners my-app --env staging fal apps delete my-app --env staging # Run functions with environment-specific secrets fal run path/to/myapp.py::MyApp --env staging ``` # fal files Source: https://fal.ai/docs/api-reference/cli/files ```bash theme={null} fal files [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal files. Options: -h, --help show this help message and exit Commands: command list (ls) List files. download Download files. upload Upload files. upload-url Upload file from URL. mv Move or rename a remote file or directory. rm Recursively remove a remote file or directory. ``` ## List ```bash theme={null} fal files list [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] [path] List files. Positional Arguments: path The path to list Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Download ```bash theme={null} fal files download [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] remote_path local_path Download files. Positional Arguments: remote_path Remote path to download local_path Local path to download to Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Upload ```bash theme={null} fal files upload [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] local_path remote_path Upload files. Positional Arguments: local_path Local path to upload remote_path Remote path to upload to Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Upload URL ```bash theme={null} fal files upload-url [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] url remote_path Upload file from URL. Positional Arguments: url URL to upload remote_path Remote path to upload to Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Move ```bash theme={null} fal files mv [-h] [--team TEAM] source destination Move or rename a remote file or directory. Positional Arguments: source Remote source path destination Remote destination path Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Remove ```bash theme={null} fal files rm [-h] [--team TEAM] path Recursively remove a remote file or directory. Positional Arguments: path Remote path Options: -h, --help show this help message and exit --team TEAM The team to use. ``` # CLI Reference Source: https://fal.ai/docs/api-reference/cli/index Complete reference for the fal command-line interface The fal CLI is the primary tool for deploying and managing your fal applications. ## Installation ```bash theme={null} pip install fal ``` ## Authentication ```bash theme={null} fal auth login ``` ## Commands | Command | Description | | ----------------------------------------------------- | -------------------------------- | | [`fal auth`](/docs/api-reference/cli/auth) | Authenticate with fal | | [`fal deploy`](/docs/api-reference/cli/deploy) | Deploy an application | | [`fal run`](/docs/api-reference/cli/run) | Run a function | | [`fal apps`](/docs/api-reference/cli/apps/list) | Manage applications | | [`fal environments`](/docs/api-reference/cli/environments) | Manage environments | | [`fal keys`](/docs/api-reference/cli/keys) | Manage API keys | | [`fal secrets`](/docs/api-reference/cli/secrets) | Manage secrets | | [`fal files`](/docs/api-reference/cli/files) | Manage files in /data | | [`fal queue`](/docs/api-reference/cli/queue) | Manage queued requests | | [`fal runners`](/docs/api-reference/cli/runners) | Manage runners | | [`fal api`](/docs/api-reference/cli/api) | Call a fal API endpoint directly | | [`fal account`](/docs/api-reference/cli/teams) | Manage accounts | | [`fal doctor`](/docs/api-reference/cli/doctor) | Diagnose issues | | [`fal create`](/docs/api-reference/cli/create) | Create a new project | | [`fal profile`](/docs/api-reference/cli/profile) | Manage profiles | # Installation Source: https://fal.ai/docs/api-reference/cli/installation ## Install latest official version ```bash theme={null} pip install fal ``` ## Install upstream version ```bash theme={null} pip install git+https://github.com/fal-ai/fal#subdirectory=projects/fal ``` ## Install development version from a git revision ```bash theme={null} pip install git+https://github.com/fal-ai/fal@75fe22f19cf61c7b6488d919d9a8c4bcb3433b42#subdirectory=projects/fal ``` ## Install development version from a git tag ```bash theme={null} pip install git+https://github.com/fal-ai/fal@fal_v1.10.0#subdirectory=projects/fal ``` ## Install development version from a git branch ```bash theme={null} pip install git+https://github.com/fal-ai/fal@main#subdirectory=projects/fal ``` # fal keys Source: https://fal.ai/docs/api-reference/cli/keys ```bash theme={null} Usage: fal keys [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal keys. Options: -h, --help show this help message and exit Commands: command create Create a key. list List keys. revoke Revoke key. ``` ## Create ```bash theme={null} Usage: fal keys create [-h] [--debug] [--pdb] [--cprofile] --scope {ADMIN,API} [--desc DESC] Create a key. Options: -h, --help show this help message and exit --scope {ADMIN,API} The privilege scope of the key. --desc DESC Key description (e.g. "My Test Key") ``` ## List ```bash theme={null} Usage: fal keys list [-h] [--debug] [--pdb] [--cprofile] List keys. Options: -h, --help show this help message and exit ``` ## Revoke ```bash theme={null} Usage: fal keys revoke [-h] [--debug] [--pdb] [--cprofile] key_id Revoke key. Positional Arguments: key_id Key ID. Options: -h, --help show this help message and exit ``` # fal profile Source: https://fal.ai/docs/api-reference/cli/profile ### Managing Profiles The `fal` CLI allows you to manage multiple profiles, making it easy to switch between different fal accounts. This is particularly useful if you have multiple environments or projects. #### Adding a New Profile To add a new profile, set it as the default and then add the key: ```sh theme={null} ❯ fal profile set example Default profile set to example. No key set for profile. Use fal profile key to set a key. ❯ fal profile key Enter the key: invalid Invalid key. The key must be in the format key:value. Enter the key: 112f05b4-6ee8-4d06-bdb1-7ba38789ef8e:954285993fa8e651dac37a03ea2efbc9 Key set for profile example. ``` **Note:** The key used in the example above is no longer valid. 😉 #### Listing Profiles To list all available profiles, use the `fal profile list` command: ```sh theme={null} ❯ fal profile list ``` | Default | Profile | Settings | | ------- | ------- | -------- | | | me | key | | | comfy | key | | \* | example | key | #### Setting a Default Profile To set a default profile, use the `fal profile set` command followed by the profile name: ```sh theme={null} ❯ fal profile set comfy Default profile set to comfy. ❯ fal profile list ``` | Default | Profile | Settings | | ------- | ------- | -------- | | | me | key | | \* | comfy | key | | | example | key | After setting the default profile, you can directly access the account information without specifying the profile name. ```sh theme={null} ❯ fal app list ``` | Name | Revision | Auth | Min Concurrency | Max Concurrency | Max Multiplexing | Keep Alive | Request Timeout | Startup Timeout | Machine Type | Runners | Regions | | ------ | ------------------ | ------ | --------------- | --------------- | ---------------- | ---------- | --------------- | --------------- | ------------ | ------- | ------- | | my-app | 11111111-2222-333… | shared | 0 | 10 | 1 | 300 | 3600 | 600 | ........ | 0 | | #### Deleting a Profile To delete a profile, use the `fal profile delete` command followed by the profile name: ```sh theme={null} ❯ fal profile delete example Profile example deleted. ``` ## Command Reference ```bash theme={null} Usage: fal profile [-h] command ... Profile management. Commands: command list List all profiles. set Set default profile. If the profile doesn't exist, you'll be prompted to create it. unset Unset default profile. key Set key for profile. host Set fal host. create Create a new profile. delete Delete profile. ``` `fal profiles` is an alias for `fal profile`. ### create Create a new named profile and set it as the default: ```bash theme={null} fal profile create ``` If the profile already exists the command is a no-op. After creation you'll typically run `fal profile key` to attach an API key. ### unset Clear the default profile selection: ```bash theme={null} fal profile unset ``` After unsetting, `fal` falls back to environment variables (`FAL_KEY`, `FAL_HOST`). ### host Override the fal API host for the active profile. Most users don't need this — it's primarily useful for self-hosted or staging deployments: ```bash theme={null} fal profile host ``` ### list ```bash theme={null} Usage: fal profile list [-h] [--output {pretty,json}] [--json] ``` Supports JSON output for scripting: ```bash theme={null} fal profile list --json ``` # fal queue Source: https://fal.ai/docs/api-reference/cli/queue Manage application queues. ```bash theme={null} Usage: fal queue [-h] command ... Manage application queues. Options: -h, --help show this help message and exit Commands: command size Get queue size for an application. flush Flush all pending requests in an application queue. ``` ## Size ```bash theme={null} Usage: fal queue size [-h] [--output {pretty,json}] [--json] [--team TEAM] [--by-user] app_name Get queue size for an application. Positional Arguments: app_name Application name (do not prefix with owner). Options: -h, --help show this help message and exit --team TEAM The team to use. --by-user Group queue size by user. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` ## Flush ```bash theme={null} Usage: fal queue flush [-h] [--team TEAM] [--caller-user-id CALLER_USER_ID] app_name Flush all pending requests in an application queue. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. --caller-user-id CALLER_USER_ID Only flush requests from this user ID. If not provided, all requests will be flushed. ``` # fal run Source: https://fal.ai/docs/api-reference/cli/run ```bash theme={null} Usage: fal run [-h] [--team TEAM] [--no-cache] [--app-name APP_NAME] [--auth AUTH] [--env ENV] [--local] [--machine-type MACHINE_TYPE] [--limit-max-requests LIMIT_MAX_REQUESTS] func_ref Run fal function. Positional Arguments: func_ref Function reference. Configure team in pyproject.toml for app names. Options: -h, --help show this help message and exit --team TEAM The team to use. --no-cache Do not use the cache for the environment build. --app-name APP_NAME Application name to run with. --auth AUTH Application authentication mode (private, public, shared), defaults to public. --env ENV Target environment (defaults to main). --local Run locally without serverless. --machine-type MACHINE_TYPE Machine type to use for this run. --limit-max-requests LIMIT_MAX_REQUESTS For fal.App runs, gracefully stop the server after serving N requests. Examples: fal run path/to/myfile.py::myfunc fal run path/to/myfile.py::myfunc --env staging fal run path/to/myfile.py::MyApp --auth private fal run path/to/myfile.py::MyApp --local fal run path/to/myfile.py::MyApp --machine-type GPU-A100 ``` `fal run` ignores the `auth` set on `fal.App` and in `pyproject.toml` and defaults to `public` so the app is reachable for testing. Pass `--auth` to override. In a future major release the default will become `private` and the `fal.App`/`pyproject.toml` value will be respected. ## Authentication Modes The `--auth` flag controls who can access your app while it's running: * **`public`** (default for `fal run`): Anyone can call your app without authentication. You pay for all usage. * **`private`**: Only you (or your team) can call the app. Requires a valid API key. * **`shared`**: Any authenticated fal user can call the app. By default, `fal run` uses `public` mode for easy testing during development. # fal runners Source: https://fal.ai/docs/api-reference/cli/runners ```bash theme={null} Usage: fal runners [-h] command ... Manage fal runners. Options: -h, --help show this help message and exit Commands: command stop Stop a runner gracefully. kill Kill a runner. list List runners. logs (log) Show logs for a runner. shell Open a shell on a runner. exec Execute a command on a runner. ``` ## List ```bash theme={null} Usage: fal runners list [-h] [--team TEAM] [--since SINCE] [--state {all,idle,running,pending,setup,crash_backoff,terminated} [...]] [--output {pretty,json}] [--json] List runners. Options: -h, --help show this help message and exit --team TEAM The team to use. --since SINCE Show terminated runners since the given time. Accepts 'now', relative like '30m', '1h', '1d', or an ISO timestamp. Max 24 hours. --state {all,idle,running,pending,setup,crash_backoff,terminated} [{all,idle,running,pending,setup,crash_backoff,terminated} ...] Filter by runner state(s). Choose one or more, or 'all' (default). Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` The runner table displays the following columns: * **Alias** — Application name * **Machine Type** — Hardware type (e.g. `GPU-A100`, `GPU-H100`) * **Runner ID** — Unique runner identifier * **In Flight Requests** — Number of active requests * **Expires In** — Time until runner expires * **Uptime** — How long the runner has been running * **Revision** — Application revision * **State** — Current runner state ## Logs ```bash theme={null} Usage: fal runners logs [-h] [--output {pretty,json}] [--json] [--team TEAM] [--search SEARCH] [--since SINCE] [--until UNTIL] [--follow] [--lines LINES] id Show logs for a runner. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. --search SEARCH Search for string in logs. --since SINCE Show logs since the given time. Accepts 'now', relative like '30m', '1h', or an ISO timestamp. Defaults to runner start time or to '1m ago' in --follow mode. --until UNTIL Show logs until the given time. Accepts 'now', relative like '30m', '1h', or an ISO timestamp. Defaults to runner finish time or 'now' if it is still running. --follow, -f Follow logs live. If --since is not specified, implies '--since 1m ago'. --lines, -n LINES Only show latest N log lines. If '+' prefix is used, show oldest N log lines. Ignored if --follow is used. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` ## Stop ```bash theme={null} Usage: fal runners stop [-h] [--team TEAM] id Stop a runner gracefully. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Kill ```bash theme={null} Usage: fal runners kill [-h] [--team TEAM] id Kill a runner. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Shell ```bash theme={null} Usage: fal runners shell [-h] [--team TEAM] id Open an interactive shell session inside a running runner. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ### Use Cases * **Debug running code**: Inspect the runtime environment of a live runner * **Check dependencies**: Verify installed packages and their versions * **Examine state**: Inspect files, environment variables, and runtime state * **Troubleshoot issues**: Diagnose problems in production runners ### Example Connect to a running runner: ```bash theme={null} # Get runner ID from runners list fal runners list # Connect to the runner fal runners shell runner_abc123xyz ``` Once connected, you have full shell access within the runner's container environment. Press `Ctrl+D` or type `exit` to disconnect. ## Exec Run a one-off command on a runner without opening an interactive shell. ```bash theme={null} Usage: fal runners exec [-h] [--team TEAM] [-it] id [command ...] Execute a command on a runner. Positional Arguments: id Runner ID. command Command to execute (after `--`). Options: -h, --help show this help message and exit --team TEAM The team to use. -it, --interactive Allocate a TTY and attach stdin (interactive mode). ``` The command and its arguments are passed after a `--` separator so they aren't parsed as flags by the `fal` CLI. ### Examples ```bash theme={null} # Print environment variables on the runner fal runners exec runner_abc123xyz -- env # Tail an arbitrary log file inside the container fal runners exec runner_abc123xyz -- tail -f /var/log/my-app.log # Run an interactive Python REPL fal runners exec runner_abc123xyz -it -- python ``` # fal secrets Source: https://fal.ai/docs/api-reference/cli/secrets ```bash theme={null} Usage: fal secrets [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal secrets. Options: -h, --help show this help message and exit Commands: command set Set a secret. list List secrets. unset Unset a secret. ``` ## Set ```bash theme={null} Usage: fal secrets set [-h] [--debug] [--pdb] [--cprofile] [--env ENV] NAME=VALUE [NAME=VALUE ...] Set a secret. Positional Arguments: NAME=VALUE Secret NAME=VALUE pairs. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Examples: fal secrets set HF_TOKEN=hf_*** fal secrets set API_KEY=key123 --env staging ``` ## List ```bash theme={null} Usage: fal secrets list [-h] [--debug] [--pdb] [--cprofile] [--env ENV] List secrets. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Examples: fal secrets list fal secrets list --env staging ``` ## Unset ```bash theme={null} Usage: fal secrets unset [-h] [--debug] [--pdb] [--cprofile] [--env ENV] NAME Unset a secret. Positional Arguments: NAME Secret's name. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. Examples: fal secrets unset HF_TOKEN fal secrets unset API_KEY --env staging ``` # fal account Source: https://fal.ai/docs/api-reference/cli/teams Manage and switch between the personal, team, and organization accounts you belong to. Useful when you're a member of multiple accounts and need to deploy or manage apps under a specific one. ## fal account list List all accounts you belong to: ```bash theme={null} fal account list ``` Shows your personal account along with any team and organization accounts, indicating which is currently active. Supports `--output {pretty,json}` and `--json` for machine-readable output. ## fal account set Switch to a specific account: ```bash theme={null} fal account set ``` `` may be either an account nickname or the index shown by `fal account list`. After switching, all CLI operations (`fal deploy`, `fal apps`, `fal secrets`, etc.) run under the selected account. If no `` is provided, you'll be prompted interactively. **Arguments:** | Argument | Description | | --------- | ------------------------------------------------- | | `account` | The account nickname (or list index) to switch to | **Example:** ```bash theme={null} # Switch to your company team fal account set my-company # Deploy under that team fal deploy my_app.py::MyApp ``` ## fal account unset Switch back to your personal account: ```bash theme={null} fal account unset ``` # Dart Client Source: https://fal.ai/docs/api-reference/client-libraries/dart/index fal client library for Flutter applications The `fal_client` package provides a Dart interface for calling fal AI models in Flutter applications. ## Installation ```bash theme={null} flutter pub add fal_client ``` ## Quick Start ```dart theme={null} import 'package:fal_client/fal_client.dart'; final fal = FalClient.withCredentials("YOUR_FAL_KEY"); final result = await fal.subscribe("fal-ai/flux/dev", input: { "prompt": "a cat", "seed": 6252023, "image_size": "landscape_4_3", "num_images": 4 }); print(result); ``` ## Supported Platforms * Flutter (iOS, Android, Web, Desktop) * Dart (standalone) ## API Reference Full API documentation on pub.dev Source code and examples Simple Flutter app using fal image inference # Client Libraries Source: https://fal.ai/docs/api-reference/client-libraries/index Libraries for calling fal AI models from your applications Use these libraries to call fal AI models from your applications. Available for multiple languages and platforms. Python client for fal AI models JS/TS client for web and Node.js ## Mobile & Other Platforms iOS, macOS, tvOS, watchOS Android and JVM Flutter apps # auth Source: https://fal.ai/docs/api-reference/client-libraries/javascript/auth API reference for @fal-ai/client auth *** ## Functions ### getTemporaryAuthToken ```typescript theme={null} async function getTemporaryAuthToken(app: string, config: RequiredConfig): Promise ``` Get a token to connect to the realtime endpoint. | Parameter | Type | Description | | :-------- | :--------------- | :---------- | | `app` | `string` | - | | `config` | `RequiredConfig` | - | **Returns:** `Promise` *** ## Types ### TokenProvider ```typescript theme={null} type TokenProvider = (app: string) => Promise ``` A function that provides a temporary authentication token. # client Source: https://fal.ai/docs/api-reference/client-libraries/javascript/client API reference for @fal-ai/client client ## Classes & Interfaces ### FalClient ```typescript theme={null} interface FalClient ``` The main client type, it provides access to simple API model usage, as well as access to the `queue` and `storage` APIs. | Name | Type | Description | | :---------- | :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `queue` | `QueueClient` | The queue client to interact with the queue API. | | `realtime` | `RealtimeClient` | The realtime client to interact with the realtime API and receive updates in real-time. | | `storage` | `StorageClient` | The storage client to interact with the storage API. | | `streaming` | `StreamingClient` | The streaming client to interact with the streaming API. | | `stream` | `StreamingClient["stream"]` | Calls a fal app that supports streaming and provides a streaming-capable object as a result, that can be used to get partial results through either `AsyncIterator` or through an event listener. | #### run ```typescript theme={null} run(endpointId: Id, options: RunOptions>): Promise>> ``` Runs a fal endpoint identified by its `endpointId`. | Parameter | Type | Description | | :----------- | :-------------------------- | :------------------------------------------------ | | `endpointId` | `Id` | The endpoint id, e.g. `fal-ai/fast-sdxl`. | | `options` | `RunOptions>` | The request options, including the input payload. | **Returns:** `Promise>>` #### subscribe ```typescript theme={null} subscribe(endpointId: Id, options: RunOptions> & QueueSubscribeOptions): Promise>> ``` Subscribes to updates for a specific request in the queue. | Parameter | Type | Description | | :----------- | :-------------------------------------------------- | :-------------------------------------------------------------------------- | | `endpointId` | `Id` | - The ID of the API endpoint. | | `options` | `RunOptions> & QueueSubscribeOptions` | - Options to configure how the request is run and how updates are received. | **Returns:** `Promise>>` *** ## Functions ### createFalClient ```typescript theme={null} function createFalClient(userConfig?: Config): FalClient ``` Creates a new reference of the `FalClient`. | Parameter | Type | Description | | :----------- | :------- | :------------------------------------------------------- | | `userConfig` | `Config` | Optional configuration to override the default settings. | **Returns:** `FalClient` # JavaScript Client Source: https://fal.ai/docs/api-reference/client-libraries/javascript/index API reference for @fal-ai/client The `@fal-ai/client` package provides a TypeScript/JavaScript interface for calling fal AI models. ## Installation ```bash theme={null} npm install @fal-ai/client ``` ## Quick Start ```typescript theme={null} import { fal } from "@fal-ai/client"; const result = await fal.subscribe("fal-ai/flux/dev", { input: { prompt: "a cat wearing a hat", image_size: "landscape_4_3" }, logs: true, onQueueUpdate: (status) => console.log(`Status: ${status.status}`) }); console.log(result.data.images[0].url); ``` ## API Overview | Method | Description | | :----------------------- | :--------------------------------- | | `fal.run()` | Run a model synchronously | | `fal.subscribe()` | Run via queue with status updates | | `fal.stream()` | Stream partial results | | `fal.queue.submit()` | Submit to queue, get request ID | | `fal.queue.status()` | Check request status | | `fal.queue.result()` | Get completed result | | `fal.realtime.connect()` | Open realtime WebSocket connection | | `fal.storage.upload()` | Upload file to fal CDN | ## API Reference The following pages contain the auto-generated API reference for all public classes and functions in the `@fal-ai/client` package. # middleware Source: https://fal.ai/docs/api-reference/client-libraries/javascript/middleware API reference for @fal-ai/client middleware *** ## Functions ### withMiddleware ```typescript theme={null} function withMiddleware(middlewares: RequestMiddleware[]): RequestMiddleware ``` Setup a execution chain of middleware functions. | Parameter | Type | Description | | :------------ | :-------------------- | :-------------------------------- | | `middlewares` | `RequestMiddleware[]` | one or more middleware functions. | **Returns:** `RequestMiddleware` ### withProxy ```typescript theme={null} function withProxy(config: RequestProxyConfig): RequestMiddleware ``` | Parameter | Type | Description | | :-------- | :------------------- | :---------- | | `config` | `RequestProxyConfig` | - | **Returns:** `RequestMiddleware` *** ## Types ### RequestConfig ```typescript theme={null} type RequestConfig = { url: string; method: string; headers?: Record; } ``` A request configuration object. **Note:** This is a simplified version of the `RequestConfig` type from the `fetch` API. It contains only the properties that are relevant for the fal client. It also works around the fact that the `fetch` API `Request` does not support mutability, its clone method has critical limitations to our use case. ### RequestMiddleware ```typescript theme={null} type RequestMiddleware = ( request: RequestConfig, ) => Promise ``` ### RequestProxyConfig ```typescript theme={null} type RequestProxyConfig = { targetUrl: string; } ``` # queue Source: https://fal.ai/docs/api-reference/client-libraries/javascript/queue API reference for @fal-ai/client queue ## Classes & Interfaces ### QueueClient ```typescript theme={null} interface QueueClient ``` Represents a request queue with methods for submitting requests, checking their status, retrieving results, and subscribing to updates. #### submit ```typescript theme={null} submit(endpointId: Id, options: SubmitOptions>): Promise ``` Submits a request to the queue. | Parameter | Type | Description | | :----------- | :----------------------------- | :--------------------------------------------- | | `endpointId` | `Id` | - The ID of the function web endpoint. | | `options` | `SubmitOptions>` | - Options to configure how the request is run. | **Returns:** `Promise` #### status ```typescript theme={null} status(endpointId: string, options: QueueStatusOptions): Promise ``` Retrieves the status of a specific request in the queue. | Parameter | Type | Description | | :----------- | :------------------- | :--------------------------------------------- | | `endpointId` | `string` | - The ID of the function web endpoint. | | `options` | `QueueStatusOptions` | - Options to configure how the request is run. | **Returns:** `Promise` #### streamStatus ```typescript theme={null} streamStatus(endpointId: string, options: QueueStatusStreamOptions): Promise> ``` Subscribes to updates for a specific request in the queue using HTTP streaming events. | Parameter | Type | Description | | :----------- | :------------------------- | :-------------------------------------------------------------------------- | | `endpointId` | `string` | - The ID of the function web endpoint. | | `options` | `QueueStatusStreamOptions` | - Options to configure how the request is run and how updates are received. | **Returns:** `Promise>` #### subscribeToStatus ```typescript theme={null} subscribeToStatus(endpointId: string, options: QueueStatusSubscriptionOptions): Promise ``` Subscribes to updates for a specific request in the queue using polling or streaming. See `options.mode` for more details. | Parameter | Type | Description | | :----------- | :------------------------------- | :-------------------------------------------------------------------------- | | `endpointId` | `string` | - The ID of the function web endpoint. | | `options` | `QueueStatusSubscriptionOptions` | - Options to configure how the request is run and how updates are received. | **Returns:** `Promise` #### result ```typescript theme={null} result(endpointId: Id, options: BaseQueueOptions): Promise>> ``` Retrieves the result of a specific request from the queue. | Parameter | Type | Description | | :----------- | :----------------- | :--------------------------------------------- | | `endpointId` | `Id` | - The ID of the function web endpoint. | | `options` | `BaseQueueOptions` | - Options to configure how the request is run. | **Returns:** `Promise>>` #### cancel ```typescript theme={null} cancel(endpointId: string, options: BaseQueueOptions): Promise ``` Cancels a request in the queue. | Parameter | Type | Description | | :----------- | :----------------- | :-------------------------------------------------------------------------- | | `endpointId` | `string` | - The ID of the function web endpoint. | | `options` | `BaseQueueOptions` | - Options to configure how the request is run and how updates are received. | **Returns:** `Promise` *** ## Types ### QueuePriority ```typescript theme={null} type QueuePriority = "low" | "normal" ``` ### QueueStatusSubscriptionOptions ```typescript theme={null} type QueueStatusSubscriptionOptions = QueueStatusOptions & QueueModeOptions & Omit ``` ### QueueSubscribeOptions ```typescript theme={null} type QueueSubscribeOptions = QueueCommonSubscribeOptions & QueueModeOptions ``` Options for subscribing to the request queue. ### SubmitOptions ```typescript theme={null} type SubmitOptions = RunOptions & { /** * The URL to send a webhook notification to when the request is completed. * @see WebHookResponse */ webhookUrl?: string; /** * The priority of the request. It defaults to `normal`. * This will be sent as the `x-fal-queue-priority` header. * * @see QueuePriority */ priority?: QueuePriority; /** * A hint for the runner to use when processing the request. * This will be sent as the `x-fal-runner-hint` header. */ hint?: string; /** * Server-side request timeout in seconds. Limits total time spent waiting * before processing starts (includes queue wait, retries, and routing). * Does not apply once the application begins processing. * * This will be sent as the `x-fal-request-timeout` header. */ startTimeout?: number; /** * Additional HTTP headers to include in the submit request. * * Note: `priority`, `hint`, `startTimeout`, and `objectLifecycle` will override the following headers: * - `x-fal-queue-priority` * - `x-fal-runner-hint` * - `x-fal-request-timeout` * - `x-fal-object-lifecycle-preference` */ headers?: Record; } ``` Options for submitting a request to the queue. ### QueueStatusOptions ```typescript theme={null} type QueueStatusOptions = BaseQueueOptions & { /** * If `true`, the response will include the logs for the request. * Defaults to `false`. */ logs?: boolean; } ``` ### QueueStatusStreamOptions ```typescript theme={null} type QueueStatusStreamOptions = QueueStatusOptions & { /** * The connection mode to use for streaming updates. It defaults to `server`. * Set to `client` if your server proxy doesn't support streaming. */ connectionMode?: StreamingConnectionMode; } ``` # realtime Source: https://fal.ai/docs/api-reference/client-libraries/javascript/realtime API reference for @fal-ai/client realtime ## Classes & Interfaces ### RealtimeConnection ```typescript theme={null} interface RealtimeConnection ``` A connection object that allows you to `send` request payloads to a realtime endpoint. #### send ```typescript theme={null} send(input: Input & Partial): void ``` | Parameter | Type | Description | | :-------- | :------------------------------- | :---------- | | `input` | `Input & Partial` | - | #### close ```typescript theme={null} close(): void ``` ### RealtimeConnectionHandler ```typescript theme={null} interface RealtimeConnectionHandler ``` Options for connecting to the realtime endpoint. | Name | Type | Description | | :------------------------ | :------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `connectionKey?` | `string` | The connection key. This is used to reuse the same connection across multiple calls to `connect`. This is particularly useful in contexts where the connection is established as part of a component lifecycle (e.g. React) and the component is re-rendered multiple times. | | `clientOnly?` | `boolean` | If `true`, the connection will only be established on the client side. This is useful for frameworks that reuse code for both server-side rendering and client-side rendering (e.g. Next.js). This is set to `true` by default when running on React in the server. Otherwise, it is set to `false`. Note that more SSR frameworks might be automatically detected in the future. In the meantime, you can set this to `true` when needed. | | `throttleInterval?` | `number` | The throtle duration in milliseconds. This is used to throtle the calls to the `send` function. Realtime apps usually react to user input, which can be very frequent (e.g. fast typing or mouse/drag movements). The default value is `128` milliseconds. | | `maxBuffering?` | `number` | Configures the maximum amount of frames to store in memory before starting to drop old ones for in favor of the newer ones. It must be between `1` and `60`. The recommended is `2`. The default is `undefined` so it can be determined by the app (normally is set to the recommended setting). | | `path?` | `string` | Optional path to append after the app id. Defaults to `/realtime`. | | `encodeMessage?` | `(input: any) => Uint8Array \| string` | Optional encoder for outgoing messages. Defaults to msgpack. Should return either a `Uint8Array` (binary) or string (text frame). | | `decodeMessage?` | `(data: any) => Promise \| any` | Optional decoder for incoming messages. Defaults to msgpack with JSON support for string payloads. | | `tokenProvider?` | `TokenProvider` | A custom token provider function. When provided, this function will be used to fetch authentication tokens instead of the default internal token fetching mechanism. This is useful when you want to fetch tokens through your own backend proxy. If not provided, the default `getTemporaryAuthToken` will be used. | | `tokenExpirationSeconds?` | `number` | The token expiration time in seconds. This is used to determine when to refresh the token. The token will be refreshed at 90% of this value. Only relevant when using a custom `tokenProvider`. If a custom `tokenProvider` is used without specifying this value, automatic token refresh will be disabled. | #### onResult ```typescript theme={null} onResult(result: Output & WithRequestId): void ``` Callback function that is called when a result is received. | Parameter | Type | Description | | :-------- | :----------------------- | :--------------------------- | | `result` | `Output & WithRequestId` | - The result of the request. | #### onError ```typescript theme={null} onError(error: ApiError): void ``` Callback function that is called when an error occurs. | Parameter | Type | Description | | :-------- | :-------------- | :------------------------- | | `error` | `ApiError` | - The error that occurred. | ### RealtimeClient ```typescript theme={null} interface RealtimeClient ``` #### connect ```typescript theme={null} connect(app: string, handler: RealtimeConnectionHandler): RealtimeConnection ``` Connect to the realtime endpoint. The default implementation uses WebSockets to connect to fal function endpoints that support WSS. | Parameter | Type | Description | | :-------- | :---------------------------------- | :--------------------------- | | `app` | `string` | the app alias or identifier. | | `handler` | `RealtimeConnectionHandler` | the connection handler. | **Returns:** `RealtimeConnection` *** ## Functions ### createRealtimeClient ```typescript theme={null} function createRealtimeClient({ config, }: RealtimeClientDependencies): RealtimeClient ``` | Parameter | Type | Description | | :------------ | :--------------------------- | :---------- | | `{ config, }` | `RealtimeClientDependencies` | - | **Returns:** `RealtimeClient` # response Source: https://fal.ai/docs/api-reference/client-libraries/javascript/response API reference for @fal-ai/client response ## Classes & Interfaces ### ApiError ```typescript theme={null} interface ApiError ``` | Name | Type | Description | | :------------- | :------- | :---------- | | `status` | `number` | - | | `body` | `Body` | - | | `requestId` | `string` | - | | `timeoutType?` | `string` | - | ### ValidationError ```typescript theme={null} interface ValidationError ``` #### getFieldErrors ```typescript theme={null} getFieldErrors(field: string): ValidationErrorInfo[] ``` | Parameter | Type | Description | | :-------- | :------- | :---------- | | `field` | `string` | - | **Returns:** `ValidationErrorInfo[]` *** ## Functions ### defaultResponseHandler ```typescript theme={null} async function defaultResponseHandler(response: Response): Promise ``` | Parameter | Type | Description | | :--------- | :--------- | :---------- | | `response` | `Response` | - | **Returns:** `Promise` ### resultResponseHandler ```typescript theme={null} async function resultResponseHandler(response: Response): Promise> ``` | Parameter | Type | Description | | :--------- | :--------- | :---------- | | `response` | `Response` | - | **Returns:** `Promise>` *** ## Types ### ResponseHandler ```typescript theme={null} type ResponseHandler = (response: Response) => Promise ``` ### ResponseHandlerCreator ```typescript theme={null} type ResponseHandlerCreator = ( config: RequiredConfig, ) => ResponseHandler ``` # retry Source: https://fal.ai/docs/api-reference/client-libraries/javascript/retry API reference for @fal-ai/client retry ## Classes & Interfaces ### RetryMetrics ```typescript theme={null} interface RetryMetrics ``` Retry metrics for tracking retry attempts | Name | Type | Description | | :-------------- | :------- | :---------- | | `totalAttempts` | `number` | - | | `totalDelay` | `number` | - | | `lastError?` | `any` | - | *** ## Functions ### isRetryableError ```typescript theme={null} function isRetryableError(error: any, retryableStatusCodes: number[]): boolean ``` Determines if an error is retryable based on the status code. User-specified timeouts (504 with X-Fal-Request-Timeout-Type: user) are NOT retryable. | Parameter | Type | Description | | :--------------------- | :--------- | :---------- | | `error` | `any` | - | | `retryableStatusCodes` | `number[]` | - | **Returns:** `boolean` ### calculateBackoffDelay ```typescript theme={null} function calculateBackoffDelay(attempt: number, baseDelay: number, maxDelay: number, backoffMultiplier: number, enableJitter: boolean): number ``` Calculates the backoff delay for a given attempt using exponential backoff | Parameter | Type | Description | | :------------------ | :-------- | :---------- | | `attempt` | `number` | - | | `baseDelay` | `number` | - | | `maxDelay` | `number` | - | | `backoffMultiplier` | `number` | - | | `enableJitter` | `boolean` | - | **Returns:** `number` ### executeWithRetry ```typescript theme={null} async function executeWithRetry(operation: () => Promise, options: RetryOptions, onRetry?: (attempt: number, error: any, delay: number) => void): Promise<{ result: T; metrics: RetryMetrics }> ``` Executes an operation with retry logic and returns both result and metrics | Parameter | Type | Description | | :---------- | :----------------------------------------------------- | :---------- | | `operation` | `() => Promise` | - | | `options` | `RetryOptions` | - | | `onRetry` | `(attempt: number, error: any, delay: number) => void` | - | **Returns:** `Promise<{ result: T; metrics: RetryMetrics }>` *** ## Types ### RetryOptions ```typescript theme={null} type RetryOptions = { maxRetries: number; baseDelay: number; maxDelay: number; backoffMultiplier: number; retryableStatusCodes: number[]; enableJitter: boolean; } ``` # storage Source: https://fal.ai/docs/api-reference/client-libraries/javascript/storage API reference for @fal-ai/client storage ## Classes & Interfaces ### StorageSettings ```typescript theme={null} interface StorageSettings ``` Configuration for object lifecycle and storage behavior. | Name | Type | Description | | :---------- | :----------------- | :------------------------------------------------------------------------------------------------------------------------------------ | | `expiresIn` | `ObjectExpiration` | The expiration time for the stored files (images, videos, etc.). You can specify one of the enumerated values or a number of seconds. | ### StorageClient ```typescript theme={null} interface StorageClient ``` File support for the client. This interface establishes the contract for uploading files to the server and transforming the input to replace file objects with URLs. | Name | Type | Description | | :--------------- | :------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `upload` | `(file: Blob, options?: UploadOptions) => Promise` | Upload a file to the server. Returns the URL of the uploaded file. | | `transformInput` | `(input: Record) => Promise>` | Transform the input to replace file objects with URLs. This is used to transform the input before sending it to the server and ensures that the server receives URLs instead of file objects. | *** ## Functions ### getExpirationDurationSeconds ```typescript theme={null} function getExpirationDurationSeconds(lifecycle: StorageSettings): number | undefined ``` Converts an `StorageSettings` to the expiration duration in seconds. | Parameter | Type | Description | | :---------- | :---------------- | :----------------------- | | `lifecycle` | `StorageSettings` | the lifecycle preference | **Returns:** `number | undefined` ### buildObjectLifecycleHeaders ```typescript theme={null} function buildObjectLifecycleHeaders(lifecycle: StorageSettings | undefined): Record ``` Builds the headers for the Object Lifecycle preference to be used in API requests. This is used by the queue and run APIs to control the lifecycle of generated objects. | Parameter | Type | Description | | :---------- | :----------------------------- | :----------------------- | | `lifecycle` | `StorageSettings \| undefined` | the lifecycle preference | **Returns:** `Record` ### createStorageClient ```typescript theme={null} function createStorageClient({ config, }: StorageClientDependencies): StorageClient ``` | Parameter | Type | Description | | :------------ | :-------------------------- | :---------- | | `{ config, }` | `StorageClientDependencies` | - | **Returns:** `StorageClient` *** ## Types ### UploadOptions ```typescript theme={null} type UploadOptions = { /** * Custom lifecycle configuration for the uploaded file. * This object will be sent as the X-Fal-Object-Lifecycle header. */ lifecycle?: StorageSettings; } ``` Options for uploading a file. # streaming Source: https://fal.ai/docs/api-reference/client-libraries/javascript/streaming API reference for @fal-ai/client streaming ## Classes & Interfaces ### FalStream ```typescript theme={null} interface FalStream ``` The class representing a streaming response. With t | Name | Type | Description | | :------------------- | :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `config` | `RequiredConfig` | - | | `endpointId` | `string` | - | | `url` | `string` | - | | `options` | `StreamOptions` | - | | `listeners` | `Map` | - | | `buffer` | `Output[]` | - | | `currentData` | `Output \| undefined` | - | | `lastEventTimestamp` | `any` | - | | `streamClosed` | `any` | - | | `_requestId` | `string \| null` | - | | `donePromise` | `Promise` | - | | `abortController` | `any` | - | | `start` | `any` | - | | `handleResponse` | `any` | - | | `handleError` | `any` | - | | `on` | `any` | - | | `emit` | `any` | - | | `done` | `any` | Gets a reference to the `Promise` that indicates whether the streaming is done or not. Developers should always call this in their apps to ensure the request is over. An alternative to this, is to use `on('done')` in case your application architecture works best with event listeners. | | `abort` | `any` | Aborts the streaming request. **Note:** This method is noop in case the request is already done. | #### `[Symbol.asyncIterator]` ```typescript theme={null} async [Symbol.asyncIterator](): any ``` **Returns:** `any` ### StreamingClient ```typescript theme={null} interface StreamingClient ``` The streaming client interface. #### stream ```typescript theme={null} stream(endpointId: Id, options: StreamOptions>): Promise, OutputType>> ``` Calls a fal app that supports streaming and provides a streaming-capable object as a result, that can be used to get partial results through either `AsyncIterator` or through an event listener. | Parameter | Type | Description | | :----------- | :----------------------------- | :------------------------------------------------ | | `endpointId` | `Id` | the endpoint id, e.g. `fal-ai/llavav15-13b`. | | `options` | `StreamOptions>` | the request options, including the input payload. | **Returns:** `Promise, OutputType>>` *** ## Functions ### createStreamingClient ```typescript theme={null} function createStreamingClient({ config, storage, }: StreamingClientDependencies): StreamingClient ``` | Parameter | Type | Description | | :--------------------- | :---------------------------- | :---------- | | `{ config, storage, }` | `StreamingClientDependencies` | - | **Returns:** `StreamingClient` *** ## Types ### StreamingConnectionMode ```typescript theme={null} type StreamingConnectionMode = "client" | "server" ``` ### StreamOptions ```typescript theme={null} type StreamOptions = { /** * The endpoint URL. If not provided, it will be generated from the * `endpointId` and the `queryParams`. */ readonly url?: string; /** * The API input payload. */ readonly input?: Input; /** * The query parameters to be sent with the request. */ readonly queryParams?: Record; /** * The maximum time interval in milliseconds between stream chunks. Defaults to 15s. */ readonly timeout?: number; /** * Whether it should auto-upload File-like types to fal's storage * or not. */ readonly autoUpload?: boolean; /** * The HTTP method, defaults to `post`; */ readonly method?: "get" | "post" | "put" | "delete" | string; /** * The content type the client accepts as response. * By default this is set to `text/event-stream`. */ readonly accept?: string; /** * The streaming connection mode. This is used to determine * whether the streaming will be done from the browser itself (client) * or through your own server, either when running on NodeJS or when * using a proxy that supports streaming. * * It defaults to `server`. Set to `client` if your server proxy doesn't * support streaming. */ readonly connectionMode?: StreamingConnectionMode; /** * The signal to abort the request. */ readonly signal?: AbortSignal; /** * A custom token provider function. Only used when `connectionMode` is `"client"`. * When provided, this function will be used to fetch authentication tokens * instead of the default internal token fetching mechanism. */ readonly tokenProvider?: TokenProvider; } ``` The stream API options. It requires the API input and also offers configuration options. # types.client Source: https://fal.ai/docs/api-reference/client-libraries/javascript/types.client API reference for @fal-ai/client types.client *** ## Types ### EndpointType ```typescript theme={null} type EndpointType = keyof EndpointTypeMap | (string & {}) ``` ### InputType ```typescript theme={null} type InputType = T extends keyof EndpointTypeMap ? EndpointTypeMap[T]["input"] : Record ``` ### OutputType ```typescript theme={null} type OutputType = T extends keyof EndpointTypeMap ? EndpointTypeMap[T]["output"] : any ``` # types.common Source: https://fal.ai/docs/api-reference/client-libraries/javascript/types.common API reference for @fal-ai/client types.common ## Classes & Interfaces ### InQueueQueueStatus ```typescript theme={null} interface InQueueQueueStatus ``` | Name | Type | Description | | :--------------- | :----------- | :---------- | | `status` | `"IN_QUEUE"` | - | | `queue_position` | `number` | - | ### InProgressQueueStatus ```typescript theme={null} interface InProgressQueueStatus ``` | Name | Type | Description | | :------- | :-------------- | :---------- | | `status` | `"IN_PROGRESS"` | - | | `logs` | `RequestLog[]` | - | ### CompletedQueueStatus ```typescript theme={null} interface CompletedQueueStatus ``` | Name | Type | Description | | :--------- | :------------- | :---------- | | `status` | `"COMPLETED"` | - | | `logs` | `RequestLog[]` | - | | `metrics?` | `Metrics` | - | *** ## Functions ### isQueueStatus ```typescript theme={null} function isQueueStatus(obj: any): obj is QueueStatus ``` | Parameter | Type | Description | | :-------- | :---- | :---------- | | `obj` | `any` | - | **Returns:** `obj is QueueStatus` ### isCompletedQueueStatus ```typescript theme={null} function isCompletedQueueStatus(obj: any): obj is CompletedQueueStatus ``` | Parameter | Type | Description | | :-------- | :---- | :---------- | | `obj` | `any` | - | **Returns:** `obj is CompletedQueueStatus` *** ## Types ### Result ```typescript theme={null} type Result = { data: T; requestId: string; } ``` Represents an API result, containing the data, the request ID and any other relevant information. ### RunOptions ```typescript theme={null} type RunOptions = { /** * The function input. It will be submitted either as query params * or the body payload, depending on the `method`. */ readonly input?: Input; /** * The HTTP method, defaults to `post`; */ readonly method?: "get" | "post" | "put" | "delete" | string; /** * The abort signal to cancel the request. */ readonly abortSignal?: AbortSignal; /** * Object lifecycle configuration for controlling how long generated objects * (images, files, etc.) remain available before expiring. * * @see StorageSettings * @see https://docs.fal.ai/model-apis/model-endpoints/queue#object-lifecycle */ readonly storageSettings?: StorageSettings; /** * Server-side request timeout in seconds. Limits total time spent waiting * before processing starts (includes queue wait, retries, and routing). * Does not apply once the application begins processing. * * This will be sent as the `x-fal-request-timeout` header. */ readonly startTimeout?: number; } ``` The function input and other configuration when running the function, such as the HTTP method to use. ### UrlOptions ```typescript theme={null} type UrlOptions = { /** * If `true`, the function will use the queue to run the function * asynchronously and return the result in a separate call. This * influences how the URL is built. */ readonly subdomain?: string; /** * The query parameters to include in the URL. */ readonly query?: Record; /** * The path to append to the function URL. */ path?: string; } ``` ### RequestLog ```typescript theme={null} type RequestLog = { message: string; level: "STDERR" | "STDOUT" | "ERROR" | "INFO" | "WARN" | "DEBUG"; source: "USER"; timestamp: string; // Using string to represent date-time format, but you could also use 'Date' type if you're going to construct Date objects. } ``` ### Metrics ```typescript theme={null} type Metrics = { inference_time: number | null; } ``` ### QueueStatus ```typescript theme={null} type QueueStatus = | InProgressQueueStatus | CompletedQueueStatus | InQueueQueueStatus ``` ### ValidationErrorInfo ```typescript theme={null} type ValidationErrorInfo = { msg: string; loc: Array; type: string; } ``` ### WebHookResponse ```typescript theme={null} type WebHookResponse = | { /** Indicates a successful response. */ status: "OK"; /** The payload of the response, structure determined by the Payload type. */ payload: Payload; /** Error is never present in a successful response. */ error: never; /** The unique identifier for the request. */ request_id: string; } | { /** Indicates an unsuccessful response. */ status: "ERROR"; /** The payload of the response, structure determined by the Payload type. */ payload: Payload; /** Description of the error that occurred. */ error: string; /** The unique identifier for the request. */ request_id: string; } ``` Represents the response from a WebHook request. This is a union type that varies based on the `status` property. # utils Source: https://fal.ai/docs/api-reference/client-libraries/javascript/utils API reference for @fal-ai/client utils *** ## Functions ### ensureEndpointIdFormat ```typescript theme={null} function ensureEndpointIdFormat(id: string): string ``` | Parameter | Type | Description | | :-------- | :------- | :---------- | | `id` | `string` | - | **Returns:** `string` ### parseEndpointId ```typescript theme={null} function parseEndpointId(id: string): EndpointId ``` | Parameter | Type | Description | | :-------- | :------- | :---------- | | `id` | `string` | - | **Returns:** `EndpointId` ### isValidUrl ```typescript theme={null} function isValidUrl(url: string): any ``` | Parameter | Type | Description | | :-------- | :------- | :---------- | | `url` | `string` | - | **Returns:** `any` ### throttle ```typescript theme={null} function throttle(func: T, limit: number, leading?: any): (...funcArgs: Parameters) => ReturnType | void ``` | Parameter | Type | Description | | :-------- | :------- | :---------- | | `func` | `T` | - | | `limit` | `number` | - | | `leading` | `any` | - | **Returns:** `(...funcArgs: Parameters) => ReturnType | void` ### isReact ```typescript theme={null} function isReact(): any ``` Not really the most optimal way to detect if we're running in React, but the idea here is that we can support multiple rendering engines (starting with React), with all their peculiarities, without having to add a dependency or creating custom integrations (e.g. custom hooks). Yes, a bit of magic to make things works out-of-the-box. **Returns:** `any` ### isPlainObject ```typescript theme={null} function isPlainObject(value: any): boolean ``` Check if a value is a plain object. | Parameter | Type | Description | | :-------- | :---- | :-------------------- | | `value` | `any` | - The value to check. | **Returns:** `boolean` ### sleep ```typescript theme={null} async function sleep(ms: number): Promise ``` Utility function to sleep for a given number of milliseconds | Parameter | Type | Description | | :-------- | :------- | :---------- | | `ms` | `number` | - | **Returns:** `Promise` *** ## Types ### EndpointId ```typescript theme={null} type EndpointId = { readonly owner: string; readonly alias: string; readonly path?: string; readonly namespace?: EndpointNamespace; } ``` # Kotlin / Java Client Source: https://fal.ai/docs/api-reference/client-libraries/kotlin/index fal client library for Android and JVM applications The `fal-client` packages provide Kotlin and Java interfaces for calling fal AI models on Android and JVM platforms. ## Installation ```groovy Gradle (Kotlin) theme={null} implementation 'ai.fal.client:fal-client-kotlin:0.7.1' ``` ```groovy Gradle (Java) theme={null} implementation 'ai.fal.client:fal-client:0.7.1' ``` ```xml Maven (Kotlin) theme={null} ai.fal.client fal-client-kotlin 0.7.1 ``` ```xml Maven (Java) theme={null} ai.fal.client fal-client 0.7.1 ``` **Java Async Support** If your code relies on asynchronous operations via `CompletableFuture` or `Future`, use the `ai.fal.client:fal-client-async` artifact instead. ## Quick Start ```kotlin Kotlin theme={null} import ai.fal.client.kt val fal = createFalClient() val input = mapOf( "prompt" to "a cat", "seed" to 6252023, "image_size" to "landscape_4_3", "num_images" to 4 ) val result = fal.subscribe("fal-ai/flux/dev", input, options = SubscribeOptions( logs = true )) { update -> if (update is QueueStatus.InProgress) { println(update.logs) } } ``` ```java Java theme={null} import ai.fal.client.*; import ai.fal.client.queue.*; var fal = FalClient.withEnvCredentials(); var input = Map.of( "prompt", "a cat", "seed", 6252023, "image_size", "landscape_4_3", "num_images", 4 ); var result = fal.subscribe("fal-ai/flux/dev", SubscribeOptions.builder() .input(input) .logs(true) .resultType(JsonObject.class) .onQueueUpdate(update -> { if (update instanceof QueueStatus.InProgress) { System.out.println(((QueueStatus.InProgress) update).getLogs()); } }) .build() ); ``` ## Supported Platforms * Android (API 21+) * JVM (Java 11+) * Kotlin Multiplatform (JVM target) ## API Reference JavaDoc documentation KDoc documentation Source code and examples # fal_client Source: https://fal.ai/docs/api-reference/client-libraries/python/fal_client API reference for fal_client ```python theme={null} from fal_client import ( SyncClient, AsyncClient, RealtimeConnection, AsyncRealtimeConnection, Status, Queued, InProgress, Completed, SyncRequestHandle, AsyncRequestHandle, run, subscribe_async, subscribe, submit, stream, run_async, submit_async, stream_async, realtime, realtime_async, cancel, cancel_async, status, status_async, result, result_async, encode, encode_file, encode_image, ) ``` ## Classes ### SyncClient ```python theme={null} class fal_client.SyncClient ``` | Name | Type | Default | Description | | :---------------- | :------------ | :------ | :---------- | | `key` | `str \| None` | `None` | - | | `default_timeout` | `float` | `120.0` | - | | Name | Type | Default | Description | | :---------------- | :------------ | :------ | :---------- | | `key` | `str \| None` | `None` | - | | `default_timeout` | `float` | `120.0` | - | | Name | Type | Description | | :---------- | :------------------- | :---------- | | `_executor` | `ThreadPoolExecutor` | - | #### cancel ```python theme={null} def cancel(self, application: 'str', request_id: 'str') -> 'None' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `NoneType` #### get\_handle ```python theme={null} def get_handle(self, application: 'str', request_id: 'str') -> 'SyncRequestHandle' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `SyncRequestHandle` #### realtime ```python theme={null} def realtime(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'Iterator[RealtimeConnection]' ``` | Parameter | Type | Default | Description | | :----------------- | :------------------------------- | :------------ | :---------- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `'/realtime'` | - | | `max_buffering` | `int \| None` | `None` | - | | `token_expiration` | `int` | `120` | - | | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | **Returns:** `Iterator[RealtimeConnection]` #### result ```python theme={null} def result(self, application: 'str', request_id: 'str') -> 'AnyJSON' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `dict[str, Any]` #### run ```python theme={null} def run(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' ``` Run an application with the given arguments (which will be JSON serialized). | Parameter | Type | Default | Description | | :-------------- | :------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | | `hint` | `str \| None` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `dict[str, Any]` #### status ```python theme={null} def status(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' ``` | Parameter | Type | Default | Description | | :------------ | :----- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` #### stream ```python theme={null} def stream(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None) -> 'Iterator[dict[str, Any]]' ``` Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications to see if this is supported. The function will iterate over each event that is streamed from the server. | Parameter | Type | Default | Description | | :------------ | :--------------- | :---------- | :---------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `'/stream'` | - | | `timeout` | `float \| None` | `None` | - | **Returns:** `Iterator[dict[str, Any]]` #### submit ```python theme={null} def submit(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'SyncRequestHandle' ``` Submit an application with the given arguments (which will be JSON serialized). | Parameter | Type | Default | Description | | :-------------- | :------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `webhook_url` | `str \| None` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | **Returns:** `SyncRequestHandle` #### subscribe ```python theme={null} def subscribe(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, on_enqueue: 'Optional[Callable[[str], None]]' = None, on_queue_update: 'Optional[Callable[[Status], None]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' ``` Subscribe to an application and wait for the result. | Parameter | Type | Default | Description | | :---------------- | :------------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `with_logs` | `bool` | `False` | - | | `on_enqueue` | `Optional[Callable[str, NoneType]]` | `None` | - | | `on_queue_update` | `Optional[Callable[Status, NoneType]]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | **Returns:** `dict[str, Any]` #### upload ```python theme={null} def upload(self, data: 'str | bytes', content_type: 'str', file_name: 'str | None' = None, *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None) -> 'str' ``` Upload the given data blob to the CDN and return the access URL. The content type should be specified as the second argument. Use upload\_file or upload\_image for convenience. | Parameter | Type | Default | Description | | :-------------------- | :------------------------------------------------------------------------- | :------ | :---------- | | `data` | `str \| bytes` | - | - | | `content_type` | `str` | - | - | | `file_name` | `str \| None` | `None` | - | | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | **Returns:** `str` #### upload\_file ```python theme={null} def upload_file(self, path: 'os.PathLike', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None) -> 'str' ``` Upload a file from the local filesystem to the CDN and return the access URL. | Parameter | Type | Default | Description | | :-------------------- | :------------------------------------------------------------------------- | :------ | :---------- | | `path` | `PathLike` | - | - | | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | **Returns:** `str` #### upload\_image ```python theme={null} def upload_image(self, image: 'Image.Image', format: 'str' = 'jpeg', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None) -> 'str' ``` Upload a pillow image object to the CDN and return the access URL. | Parameter | Type | Default | Description | | :-------------------- | :------------------------------------------------------- | :------- | :---------- | | `image` | `Image.Image` | - | - | | `format` | `str` | `'jpeg'` | - | | `repository` | `UploadRepositoryId \| None` | `None` | - | | `fallback_repository` | `UploadRepositoryId \| list[UploadRepositoryId] \| None` | `None` | - | #### ws\_connect ```python theme={null} def ws_connect(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '', max_buffering: 'int | None' = None, token_expiration: 'int' = 120) -> "Iterator['Connection']" ``` | Parameter | Type | Default | Description | | :----------------- | :------------ | :------ | :---------- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `''` | - | | `max_buffering` | `int \| None` | `None` | - | | `token_expiration` | `int` | `120` | - | ### AsyncClient ```python theme={null} class fal_client.AsyncClient ``` | Name | Type | Default | Description | | :---------------- | :------------ | :------ | :---------- | | `key` | `str \| None` | `None` | - | | `default_timeout` | `float` | `120.0` | - | | Name | Type | Default | Description | | :---------------- | :------------ | :------ | :---------- | | `key` | `str \| None` | `None` | - | | `default_timeout` | `float` | `120.0` | - | #### cancel ```python theme={null} async def cancel(self, application: 'str', request_id: 'str') -> 'None' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `NoneType` #### get\_handle ```python theme={null} def get_handle(self, application: 'str', request_id: 'str') -> 'AsyncRequestHandle' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `AsyncRequestHandle` #### realtime ```python theme={null} def realtime(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'AsyncIterator[AsyncRealtimeConnection]' ``` | Parameter | Type | Default | Description | | :----------------- | :------------------------------- | :------------ | :---------- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `'/realtime'` | - | | `max_buffering` | `int \| None` | `None` | - | | `token_expiration` | `int` | `120` | - | | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | **Returns:** `AsyncIterator[AsyncRealtimeConnection]` #### result ```python theme={null} async def result(self, application: 'str', request_id: 'str') -> 'AnyJSON' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `dict[str, Any]` #### run ```python theme={null} async def run(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' ``` Run an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return the result of the inference call directly. | Parameter | Type | Default | Description | | :-------------- | :------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | | `hint` | `str \| None` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `dict[str, Any]` #### status ```python theme={null} async def status(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' ``` | Parameter | Type | Default | Description | | :------------ | :----- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` #### stream ```python theme={null} def stream(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None) -> 'AsyncIterator[dict[str, Any]]' ``` Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications to see if this is supported. The function will iterate over each event that is streamed from the server. | Parameter | Type | Default | Description | | :------------ | :--------------- | :---------- | :---------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `'/stream'` | - | | `timeout` | `float \| None` | `None` | - | **Returns:** `AsyncIterator[dict[str, Any]]` #### submit ```python theme={null} async def submit(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'AsyncRequestHandle' ``` Submit an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return a handle to the request that can be used to check the status and retrieve the result of the inference call when it is done. | Parameter | Type | Default | Description | | :-------------- | :------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `webhook_url` | `str \| None` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | **Returns:** `AsyncRequestHandle` #### subscribe ```python theme={null} async def subscribe(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, on_enqueue: 'Optional[Callable[[str], None]]' = None, on_queue_update: 'Optional[Callable[[Status], None]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' ``` Subscribe to an application and wait for the result. | Parameter | Type | Default | Description | | :---------------- | :------------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `with_logs` | `bool` | `False` | - | | `on_enqueue` | `Optional[Callable[str, NoneType]]` | `None` | - | | `on_queue_update` | `Optional[Callable[Status, NoneType]]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | **Returns:** `dict[str, Any]` #### upload ```python theme={null} async def upload(self, data: 'str | bytes', content_type: 'str', file_name: 'str | None' = None, *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None) -> 'str' ``` Upload the given data blob to the CDN and return the access URL. The content type should be specified as the second argument. Use upload\_file or upload\_image for convenience. | Parameter | Type | Default | Description | | :-------------------- | :------------------------------------------------------------------------- | :------ | :---------- | | `data` | `str \| bytes` | - | - | | `content_type` | `str` | - | - | | `file_name` | `str \| None` | `None` | - | | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | **Returns:** `str` #### upload\_file ```python theme={null} async def upload_file(self, path: 'os.PathLike', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None) -> 'str' ``` Upload a file from the local filesystem to the CDN and return the access URL. | Parameter | Type | Default | Description | | :-------------------- | :------------------------------------------------------------------------- | :------ | :---------- | | `path` | `PathLike` | - | - | | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | **Returns:** `str` #### upload\_image ```python theme={null} async def upload_image(self, image: 'Image.Image', format: 'str' = 'jpeg', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None) -> 'str' ``` Upload a pillow image object to the CDN and return the access URL. | Parameter | Type | Default | Description | | :-------------------- | :------------------------------------------------------- | :------- | :---------- | | `image` | `Image.Image` | - | - | | `format` | `str` | `'jpeg'` | - | | `repository` | `UploadRepositoryId \| None` | `None` | - | | `fallback_repository` | `UploadRepositoryId \| list[UploadRepositoryId] \| None` | `None` | - | #### ws\_connect ```python theme={null} def ws_connect(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '', max_buffering: 'int | None' = None, token_expiration: 'int' = 120) -> "AsyncIterator['WebSocketClientProtocol']" ``` | Parameter | Type | Default | Description | | :----------------- | :------------ | :------ | :---------- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `''` | - | | `max_buffering` | `int \| None` | `None` | - | | `token_expiration` | `int` | `120` | - | ### RealtimeConnection ```python theme={null} class fal_client.RealtimeConnection ``` Synchronous realtime connection wrapper. | Name | Type | Default | Description | | :---------------- | :------------------------------- | :------ | :---------- | | `_ws` | `'Connection'` | - | - | | `_encode_message` | `Callable[[Any], bytes] \| None` | `None` | - | | `_decode_message` | `Callable[[bytes], Any] \| None` | `None` | - | #### close ```python theme={null} def close(self) -> 'None' ``` **Returns:** `NoneType` #### recv ```python theme={null} def recv(self) -> 'dict[str, Any] | None' ``` **Returns:** `dict[str, Any] | None` #### send ```python theme={null} def send(self, arguments: 'dict[str, Any]') -> 'None' ``` | Parameter | Type | Default | Description | | :---------- | :--------------- | :------ | :---------- | | `arguments` | `dict[str, Any]` | - | - | **Returns:** `NoneType` ### AsyncRealtimeConnection ```python theme={null} class fal_client.AsyncRealtimeConnection ``` Asynchronous realtime connection wrapper. | Name | Type | Default | Description | | :---------------- | :------------------------------- | :------ | :---------- | | `_ws` | `'WebSocketClientProtocol'` | - | - | | `_encode_message` | `Callable[[Any], bytes] \| None` | `None` | - | | `_decode_message` | `Callable[[bytes], Any] \| None` | `None` | - | #### close ```python theme={null} async def close(self) -> 'None' ``` **Returns:** `NoneType` #### recv ```python theme={null} async def recv(self) -> 'dict[str, Any] | None' ``` **Returns:** `dict[str, Any] | None` #### send ```python theme={null} async def send(self, arguments: 'dict[str, Any]') -> 'None' ``` | Parameter | Type | Default | Description | | :---------- | :--------------- | :------ | :---------- | | `arguments` | `dict[str, Any]` | - | - | **Returns:** `NoneType` ### Status ```python theme={null} class fal_client.Status ``` ### Queued ```python theme={null} class fal_client.Queued ``` Indicates the request is enqueued and waiting to be processed. The position field indicates the relative position in the queue (0-indexed). > **Inherits from:** `Status` | Name | Type | Default | Description | | :--------- | :---- | :------ | :---------- | | `position` | `int` | - | - | | Name | Type | Default | Description | | :--------- | :---- | :------ | :---------- | | `position` | `int` | - | - | ### InProgress ```python theme={null} class fal_client.InProgress ``` Indicates the request is currently being processed. If the status operation called with the `with_logs` parameter set to True, the logs field will be a list of log objects. > **Inherits from:** `Status` | Name | Type | Default | Description | | :----- | :----------------------------- | :------ | :---------- | | `logs` | `list[dict[str, Any]] \| None` | - | - | | Name | Type | Default | Description | | :----- | :----------------------------- | :------ | :---------- | | `logs` | `list[dict[str, Any]] \| None` | - | - | ### Completed ```python theme={null} class fal_client.Completed ``` Indicates the request has been completed and the result can be gathered. The logs field will contain the logs if the status operation was called with the `with_logs` parameter set to True. Metrics might contain the inference time, and other internal metadata (number of tokens processed, etc.). > **Inherits from:** `Status` | Name | Type | Default | Description | | :-------- | :----------------------------- | :------ | :---------- | | `logs` | `list[dict[str, Any]] \| None` | - | - | | `metrics` | `dict[str, Any]` | - | - | | Name | Type | Default | Description | | :-------- | :----------------------------- | :------ | :---------- | | `logs` | `list[dict[str, Any]] \| None` | - | - | | `metrics` | `dict[str, Any]` | - | - | ### SyncRequestHandle ```python theme={null} class fal_client.SyncRequestHandle ``` > **Inherits from:** `_BaseRequestHandle` | Name | Type | Default | Description | | :------------- | :------- | :------ | :---------- | | `request_id` | `str` | - | - | | `response_url` | `str` | - | - | | `status_url` | `str` | - | - | | `cancel_url` | `str` | - | - | | `client` | `Client` | - | - | | Name | Type | Default | Description | | :------- | :------------- | :------ | :---------- | | `client` | `httpx.Client` | - | - | #### cancel ```python theme={null} def cancel(self) -> 'None' ``` Cancel the request. **Returns:** `NoneType` #### from\_request\_id ```python theme={null} def from_request_id(cls, client: 'httpx.Client', application: 'str', request_id: 'str') -> 'SyncRequestHandle' ``` | Parameter | Type | Default | Description | | :------------ | :------- | :------ | :---------- | | `client` | `Client` | - | - | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `SyncRequestHandle` #### get ```python theme={null} def get(self) -> 'AnyJSON' ``` Wait till the request is completed and return the result of the inference call. **Returns:** `dict[str, Any]` #### iter\_events ```python theme={null} def iter_events(self, *, with_logs: 'bool' = False, interval: 'float' = 0.1) -> 'Iterator[Status]' ``` Continuously poll for the status of the request and yield it at each interval till the request is completed. If `with_logs` is True, logs will be included in the response. | Parameter | Type | Default | Description | | :---------- | :------ | :------ | :---------- | | `with_logs` | `bool` | `False` | - | | `interval` | `float` | `0.1` | - | **Returns:** `Iterator[Status]` #### status ```python theme={null} def status(self, *, with_logs: 'bool' = False) -> 'Status' ``` Returns the status of the request (which can be one of the following: Queued, InProgress, Completed). If `with_logs` is True, logs will be included for InProgress and Completed statuses. | Parameter | Type | Default | Description | | :---------- | :----- | :------ | :---------- | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` ### AsyncRequestHandle ```python theme={null} class fal_client.AsyncRequestHandle ``` > **Inherits from:** `_BaseRequestHandle` | Name | Type | Default | Description | | :------------- | :------------ | :------ | :---------- | | `request_id` | `str` | - | - | | `response_url` | `str` | - | - | | `status_url` | `str` | - | - | | `cancel_url` | `str` | - | - | | `client` | `AsyncClient` | - | - | | Name | Type | Default | Description | | :------- | :------------------ | :------ | :---------- | | `client` | `httpx.AsyncClient` | - | - | #### cancel ```python theme={null} async def cancel(self) -> 'None' ``` Cancel the request. **Returns:** `NoneType` #### from\_request\_id ```python theme={null} def from_request_id(cls, client: 'httpx.AsyncClient', application: 'str', request_id: 'str') -> 'AsyncRequestHandle' ``` | Parameter | Type | Default | Description | | :------------ | :------------ | :------ | :---------- | | `client` | `AsyncClient` | - | - | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `AsyncRequestHandle` #### get ```python theme={null} async def get(self) -> 'AnyJSON' ``` Wait till the request is completed and return the result. **Returns:** `dict[str, Any]` #### iter\_events ```python theme={null} def iter_events(self, *, with_logs: 'bool' = False, interval: 'float' = 0.1) -> 'AsyncIterator[Status]' ``` Continuously poll for the status of the request and yield it at each interval till the request is completed. If `with_logs` is True, logs will be included in the response. | Parameter | Type | Default | Description | | :---------- | :------ | :------ | :---------- | | `with_logs` | `bool` | `False` | - | | `interval` | `float` | `0.1` | - | **Returns:** `AsyncIterator[Status]` #### status ```python theme={null} async def status(self, *, with_logs: 'bool' = False) -> 'Status' ``` Returns the status of the request (which can be one of the following: Queued, InProgress, Completed). If `with_logs` is True, logs will be included for InProgress and Completed statuses. | Parameter | Type | Default | Description | | :---------- | :----- | :------ | :---------- | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` *** ## Functions ### run ```python theme={null} def run(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' ``` Run an application with the given arguments (which will be JSON serialized). | Parameter | Type | Default | Description | | :-------------- | :------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | | `hint` | `str \| None` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `dict[str, Any]` ### subscribe\_async ```python theme={null} async def subscribe_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, on_enqueue: 'Optional[Callable[[str], None]]' = None, on_queue_update: 'Optional[Callable[[Status], None]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' ``` Subscribe to an application and wait for the result. | Parameter | Type | Default | Description | | :---------------- | :------------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `with_logs` | `bool` | `False` | - | | `on_enqueue` | `Optional[Callable[str, NoneType]]` | `None` | - | | `on_queue_update` | `Optional[Callable[Status, NoneType]]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | **Returns:** `dict[str, Any]` ### subscribe ```python theme={null} def subscribe(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, on_enqueue: 'Optional[Callable[[str], None]]' = None, on_queue_update: 'Optional[Callable[[Status], None]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' ``` Subscribe to an application and wait for the result. | Parameter | Type | Default | Description | | :---------------- | :------------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `with_logs` | `bool` | `False` | - | | `on_enqueue` | `Optional[Callable[str, NoneType]]` | `None` | - | | `on_queue_update` | `Optional[Callable[Status, NoneType]]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | **Returns:** `dict[str, Any]` ### submit ```python theme={null} def submit(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'SyncRequestHandle' ``` Submit an application with the given arguments (which will be JSON serialized). | Parameter | Type | Default | Description | | :-------------- | :------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `webhook_url` | `str \| None` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | **Returns:** `SyncRequestHandle` ### stream ```python theme={null} def stream(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None) -> 'Iterator[dict[str, Any]]' ``` Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications to see if this is supported. The function will iterate over each event that is streamed from the server. | Parameter | Type | Default | Description | | :------------ | :--------------- | :---------- | :---------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `'/stream'` | - | | `timeout` | `float \| None` | `None` | - | **Returns:** `Iterator[dict[str, Any]]` ### run\_async ```python theme={null} async def run_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' ``` Run an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return the result of the inference call directly. | Parameter | Type | Default | Description | | :-------------- | :------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | | `hint` | `str \| None` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `dict[str, Any]` ### submit\_async ```python theme={null} async def submit_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'AsyncRequestHandle' ``` Submit an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return a handle to the request that can be used to check the status and retrieve the result of the inference call when it is done. | Parameter | Type | Default | Description | | :-------------- | :------------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `str \| None` | `None` | - | | `webhook_url` | `str \| None` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | **Returns:** `AsyncRequestHandle` ### stream\_async ```python theme={null} def stream_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None) -> 'AsyncIterator[dict[str, Any]]' ``` Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications to see if this is supported. The function will iterate over each event that is streamed from the server. | Parameter | Type | Default | Description | | :------------ | :--------------- | :---------- | :---------- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `'/stream'` | - | | `timeout` | `float \| None` | `None` | - | **Returns:** `AsyncIterator[dict[str, Any]]` ### realtime ```python theme={null} def realtime(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'Iterator[RealtimeConnection]' ``` | Parameter | Type | Default | Description | | :----------------- | :------------------------------- | :------------ | :---------- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `'/realtime'` | - | | `max_buffering` | `int \| None` | `None` | - | | `token_expiration` | `int` | `120` | - | | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | **Returns:** `Iterator[RealtimeConnection]` ### realtime\_async ```python theme={null} def realtime_async(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'AsyncIterator[AsyncRealtimeConnection]' ``` | Parameter | Type | Default | Description | | :----------------- | :------------------------------- | :------------ | :---------- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `'/realtime'` | - | | `max_buffering` | `int \| None` | `None` | - | | `token_expiration` | `int` | `120` | - | | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | **Returns:** `AsyncIterator[AsyncRealtimeConnection]` ### cancel ```python theme={null} def cancel(self, application: 'str', request_id: 'str') -> 'None' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `NoneType` ### cancel\_async ```python theme={null} async def cancel_async(self, application: 'str', request_id: 'str') -> 'None' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `NoneType` ### status ```python theme={null} def status(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' ``` | Parameter | Type | Default | Description | | :------------ | :----- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` ### status\_async ```python theme={null} async def status_async(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' ``` | Parameter | Type | Default | Description | | :------------ | :----- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` ### result ```python theme={null} def result(self, application: 'str', request_id: 'str') -> 'AnyJSON' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `dict[str, Any]` ### result\_async ```python theme={null} async def result_async(self, application: 'str', request_id: 'str') -> 'AnyJSON' ``` | Parameter | Type | Default | Description | | :------------ | :---- | :------ | :---------- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `dict[str, Any]` ### encode ```python theme={null} def encode(data: 'str | bytes', content_type: 'str') -> 'str' ``` Encode the given data blob to a data URL with the specified content type. | Parameter | Type | Default | Description | | :------------- | :------------- | :------ | :---------- | | `data` | `str \| bytes` | - | - | | `content_type` | `str` | - | - | **Returns:** `str` ### encode\_file ```python theme={null} def encode_file(path: 'os.PathLike') -> 'str' ``` Encode a file from the local filesystem to a data URL with the inferred content type. | Parameter | Type | Default | Description | | :-------- | :--------- | :------ | :---------- | | `path` | `PathLike` | - | - | **Returns:** `str` ### encode\_image ```python theme={null} def encode_image(image: 'Image.Image', format: 'str' = 'jpeg') -> 'str' ``` Encode a pillow image object to a data URL with the specified format. | Parameter | Type | Default | Description | | :-------- | :------------ | :------- | :---------- | | `image` | `Image.Image` | - | - | | `format` | `str` | `'jpeg'` | - | # Python Client Source: https://fal.ai/docs/api-reference/client-libraries/python/index API reference for fal-client Python package The `fal-client` package provides a Python interface for calling fal AI models. ## Installation ```bash theme={null} pip install fal-client ``` ## Quick Start ```python theme={null} import fal_client result = fal_client.subscribe( "fal-ai/flux/dev", arguments={ "prompt": "a cat wearing a hat", "image_size": "landscape_4_3" }, with_logs=True, on_queue_update=lambda status: print(f"Status: {status}") ) print(result["images"][0]["url"]) ``` ## API Reference The following pages contain the auto-generated API reference for all public classes and functions in the `fal-client` package. # Swift Client Source: https://fal.ai/docs/api-reference/client-libraries/swift/index fal client library for iOS, macOS, tvOS, and watchOS The `fal-swift` package provides a native Swift interface for calling fal AI models on Apple platforms. ## Installation Add the package via Swift Package Manager: ```swift theme={null} .package(url: "https://github.com/fal-ai/fal-swift.git", from: "0.5.6") ``` ## Quick Start ```swift theme={null} import FalClient let result = try await fal.subscribe( to: "fal-ai/flux/dev", input: [ "prompt": "a cat", "seed": 6252023, "image_size": "landscape_4_3", "num_images": 4 ], includeLogs: true ) { update in if case let .inProgress(logs) = update { print(logs) } } ``` ## Supported Platforms * iOS 16+ * macOS 13+ * tvOS 16+ * watchOS 9+ ## API Reference Full API documentation on Swift Package Index Source code and examples # Reference Source: https://fal.ai/docs/api-reference/index Complete API and SDK reference documentation for fal Complete reference documentation for all fal SDKs and tools. Libraries for calling fal AI models from your applications Command-line interface for deploying and managing fal applications Tools for building and deploying serverless AI applications ## Overview | Section | What it's for | When to use | | :------------------- | :------------------------------------------- | :-------------------------------------------- | | **Client Libraries** | Call fal AI models and get results | You want to use fal's AI models in your app | | **CLI Reference** | Deploy, manage, and monitor fal applications | You're working with fal from the command line | | **Python SDK** | Build and deploy custom AI applications | You're deploying your own models on fal | # Authentication Source: https://fal.ai/docs/api-reference/platform-apis/authentication Platform APIs require API keys for secure access to your user or team's data. ## Generating API Keys Navigate to the dashboard keys page and generate a key from the UI: [fal.ai/dashboard/keys](https://fal.ai/dashboard/keys) ## Scopes Platform APIs may require different API key scopes. [Learn more about key-based authentication and scopes](/docs/documentation/model-apis/authentication/key-based). Most Platform APIs accept **API scope** keys. This scope is suitable for most use cases including model discovery, pricing, and analytics. Some Platform APIs require **Admin scope** keys for access to sensitive data. Check the specific Platform API documentation to see which scope is required. If you're unsure, start with an API scope key. You can always generate an Admin scope key later if needed. API keys should be kept secure and never exposed in client-side code or public repositories. ## Authentication Format Include your API key in the `Authorization` header with the `Key` prefix: ```bash theme={null} Authorization: Key YOUR_API_KEY ``` For endpoints requiring Admin scope: ```bash theme={null} Authorization: Key YOUR_ADMIN_API_KEY ``` ## Usage Examples ### cURL Using an API scope key for model listing: ```bash theme={null} curl -X GET "https://api.fal.ai/v1/models?limit=10" \ -H "Authorization: Key YOUR_API_KEY" ``` Using an Admin scope key for usage data: ```bash theme={null} curl -X GET "https://api.fal.ai/v1/models/usage" \ -H "Authorization: Key YOUR_ADMIN_API_KEY" ``` ### Python Using an API scope key: ```python theme={null} import requests headers = { "Authorization": "Key YOUR_API_KEY" } response = requests.get( "https://api.fal.ai/v1/models", headers=headers, params={"limit": 10} ) print(response.json()) ``` ### JavaScript Using an API scope key: ```javascript theme={null} const response = await fetch('https://api.fal.ai/v1/models?limit=10', { headers: { 'Authorization': 'Key YOUR_API_KEY' } }); const data = await response.json(); console.log(data); ``` ## Best Practices * Store API keys in environment variables * Use the minimum required scope for your use case * Rotate keys regularly * Keep Admin API keys secure and never expose them client-side ## Troubleshooting ### 401 Unauthorized * Verify your API key is correct * Ensure the `Authorization` header includes the `Key` prefix * Check that your API key hasn't been revoked ### 403 Forbidden Your API key may not have the required scope for the endpoint. Check the endpoint documentation to determine if it requires an Admin scope key, and generate one from the dashboard if needed. # Platform APIs for Accounts Source: https://fal.ai/docs/api-reference/platform-apis/for-accounts Programmatic access to account billing information, FOCUS-compliant cost reports, and model access controls The **fal Platform APIs** provide programmatic access to account-level billing, cost reporting, and governance, including: * **Billing information** - Retrieve account billing details and credit balances * **FOCUS reports** - Download FinOps FOCUS-compliant billing reports for cost analysis and interoperability * **Model access controls** - Export the resolved UI and API access state for each model in your organization ## Available Operations The Platform APIs provide the following endpoints for account billing, reporting, and governance: Retrieve billing information and credit balances for your account Download FOCUS-compliant billing reports from invoice or usage estimate data Export the resolved UI and API access state for each model in your organization FOCUS reports and model access controls are available to enterprise customers with the corresponding features enabled. Contact your account team or [support@fal.ai](mailto:support@fal.ai) to request access. # Platform APIs for Assets Source: https://fal.ai/docs/api-reference/platform-apis/for-assets Programmatic access to fal Assets for browsing, searching, uploading, and organizing generated media The **fal Platform APIs** provide programmatic access to fal Assets, including: * **Browse and search** - List assets, filter by media type or source, and search with text or fal-hosted media * **Uploads** - Add media to your Assets library from API or CLI-driven workflows * **Collections** - Create manual collections and add or remove assets * **Characters** - Create reusable character collections with reference images * **Tags and favorites** - Organize assets with tags and favorite state Use these APIs when you want generated outputs, uploaded references, and reusable creative assets to be available outside the dashboard. For generating new media, use the [Model APIs](/docs/documentation/model-apis/overview), then use Assets to browse, search, and organize the media that belongs in your library. ## Available Operations The Platform APIs provide the following endpoints for fal Assets: Browse and semantically search assets across media, uploads, favorites, collections, tags, and character references Upload fal-hosted media into your Assets library Retrieve a single asset by vector ID Favorite an asset by vector ID or request ID ## Collections List asset collections in your library Create a collection for organizing related assets Browse assets inside a collection Add an asset to a collection by vector ID or request ID ## Characters List character collections in your library Create a reusable character from descriptions and reference images Retrieve a character collection Mark a character collection as a favorite ## Tags List tags in your Assets library Create a tag for organizing assets Replace the full tag set for an asset Assign a tag to an asset by vector ID or request ID ## Authentication Assets endpoints require an API key in the `Authorization` header: ```bash theme={null} Authorization: Key YOUR_API_KEY ``` If generated media is not appearing in Assets, check your Assets settings in the dashboard and enable the request sources you want available in the library. # Platform APIs for Compute Source: https://fal.ai/docs/api-reference/platform-apis/for-compute Programmatic access to compute instance management, lifecycle control, and monitoring The **fal Platform APIs** provide programmatic access to platform management features for Compute, including: * **Instance management** - Create, list, and delete compute instances * **Instance details** - Retrieve detailed information about specific instances ## Available Operations The Platform APIs provide the following endpoints for managing Compute instances: List all compute instances with their current status and configuration Retrieve detailed information about a specific compute instance Create and provision a new compute instance Terminate and remove a compute instance These APIs are for **platform management** of Compute instances. For getting started with Compute, see the [Compute documentation](/docs/compute). # Platform APIs for Keys Source: https://fal.ai/docs/api-reference/platform-apis/for-keys Programmatic access to API key management, creation, and deletion The **fal Platform APIs** provide programmatic access to API key management, including: * **List keys** - Retrieve all API keys associated with your account * **Create keys** - Generate new API keys with custom aliases * **Delete keys** - Revoke and remove existing API keys ## Available Operations The Platform APIs provide the following endpoints for managing API keys: Retrieve all API keys with pagination support Generate a new API key with a friendly alias Permanently revoke and delete an API key These APIs require **admin API key** authentication. For more information on authentication, see the [Authentication](/docs/reference/platform-apis/authentication) documentation. # Platform APIs for Models Source: https://fal.ai/docs/api-reference/platform-apis/for-models Programmatic access to model metadata, pricing, usage tracking, and analytics The **fal Platform APIs** provide programmatic access to platform management features for Model APIs, including: * **Model metadata** - Search and discover available model endpoints with detailed information * **Pricing information** - Retrieve real-time pricing and estimate costs * **Usage tracking** - Access detailed usage line items with unit quantities and prices * **Analytics** - Query time-bucketed metrics for request counts, success/error rates, error-type breakdown, latency percentiles, cold boot metrics, and billable duration ## Available Operations The Platform APIs provide the following endpoints for managing Model APIs: Search and discover available model endpoints with metadata, categories, and capabilities Retrieve real-time pricing information for models Estimate costs for planned operations Access detailed usage line items with unit quantities and prices Query time-bucketed metrics for requests, success rates, error-type breakdown, latency percentiles, cold boot metrics, and billable duration List recent requests for a specific model endpoint with filters and pagination Delete IO payloads and CDN output files for a specific request These APIs are for **platform management** of Model APIs. For executing models and generating content, see the [Inference Methods](/docs/documentation/model-apis/inference) documentation. # Platform APIs for Organizations Source: https://fal.ai/docs/api-reference/platform-apis/for-organization Programmatic access to organization-wide team listings, cross-team usage records, FOCUS billing reports, and billing events The **fal Platform APIs** provide programmatic access to organization-level data spanning every team and product line, including: * **Team listings** - List all teams in your organization and identify the root team * **Usage records** - Browse cross-team, cross-product usage attributed to each team and product line * **FOCUS reports** - Download a FinOps FOCUS-compliant billing report as CSV, spanning every team in your organization * **Billing events** - Browse paginated per-request billing event records across all teams, with cost breakdowns in USD ## Available Operations The Platform APIs provide the following endpoints for organization administration: List the teams in your organization with their details, including the root team Browse paginated usage records across all teams and product lines, with per-team and per-product attribution Download a FOCUS-compliant billing report as CSV spanning every team, with per-team sub-account attribution under pooled billing Browse paginated per-request billing events across all teams, with per-team attribution and USD cost breakdowns These endpoints are available to enterprise customers with organizations enabled, and must be called with an admin API key on the organization's root team. The Organization FOCUS Report additionally requires FOCUS reports to be enabled. Contact your account team or [support@fal.ai](mailto:support@fal.ai) to request access. # Platform APIs for Serverless Source: https://fal.ai/docs/api-reference/platform-apis/for-serverless Programmatic access to serverless apps metadata, analytics, and billing ## Available Operations The Platform APIs provide the following endpoints for Serverless Apps: ## Files List the contents of the root directory of your Serverless storage. List the contents of any nested directory by providing its path. Download any file from Serverless storage. Upload a file from a URL into Serverless storage. Upload a local file into Serverless storage. ## Requests List recent requests for your serverless endpoints with filtering, sorting, and pagination. Pass `expand=billing` to include `billable_units` per request — the per-request building block for cost reporting on your deployed apps. ## Billing Per-request billing data for your serverless apps is available through the `expand=billing` parameter on [List Requests by Endpoint](/docs/platform-apis/v1/serverless/requests/by-endpoint). Each request in the response includes a `billable_units` field representing the units fal billed for that invocation. `billable_units` is the raw unit count for each request. To compute total cost, multiply by your effective per-unit price for the app. For account-level credit balance, see [Account Billing](/docs/platform-apis/v1/account/billing). ```bash Example theme={null} curl -G "https://api.fal.ai/v1/serverless/requests/by-endpoint" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "endpoint_id=your-username/your-app" \ --data-urlencode "expand=billing" ``` Sample response shape (truncated): ```json theme={null} { "items": [ { "request_id": "a1b2c3d4-...", "endpoint_id": "your-username/your-app", "ended_at": "2025-01-01T00:00:08Z", "status_code": 200, "duration": 7.8, "billable_units": 1.5 } ], "next_cursor": "Mg==", "has_more": true } ``` `billable_units` will be `null` if a billing event hasn't been recorded yet for the request (e.g., the request just completed and the billing pipeline hasn't caught up). ## Usage Time-bucketed, aggregated compute usage for the serverless apps **you own** — the machine-seconds your deployed apps consumed, priced with your machine rates and net of discounts. The aggregated counterpart to the per-request `billable_units` above. Where [List Requests by Endpoint](/docs/platform-apis/v1/serverless/requests/by-endpoint) gives you per-request billing, **Usage** gives you the rolled-up view: how many machine-seconds each of your apps consumed and what it cost, grouped by app, environment, and machine type. It reports your *own* compute spend, scoped to the apps you own. This endpoint returns billing and usage data, so it requires an **`ADMIN`-scoped API key**. A standard `API`-scoped key will receive a `403`. ### Filtering by app The `app` field in the response is your deployed app's name (e.g. `my-app-prod`). Two ways to narrow results: * **`app`** — exact match on one or more app names. Comma-separated or repeated, up to 50: `app=my-app-dev,my-app-prod`. Use the value exactly as it appears in the response. * **`search`** — case-insensitive substring match on the app name, for when you know the name but not the exact environment/version suffix: `search=my-app` returns every `my-app*` variant. Provide both to combine them (AND). Omit both to return every app you own — useful for discovering the exact names to filter on. ```bash Summary across all your apps (last 30 days) theme={null} curl -G "https://api.fal.ai/v1/serverless/usage" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "start=2025-01-01" \ --data-urlencode "end=2025-01-31" \ --data-urlencode "expand=summary" ``` ```bash One app, daily time series theme={null} curl -G "https://api.fal.ai/v1/serverless/usage" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "app=my-app-prod" \ --data-urlencode "start=2025-01-01" \ --data-urlencode "end=2025-01-31" \ --data-urlencode "timeframe=day" ``` ```bash All variants of an app by name theme={null} curl -G "https://api.fal.ai/v1/serverless/usage" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "search=my-app" \ --data-urlencode "expand=summary" ``` Sample response shape (`expand=summary`): ```json theme={null} { "summary": [ { "app": "my-app-prod", "environment": null, "machine_type": "GPU-H100", "unit": "second", "quantity": 9702.47, "unit_price": 0.00125, "cost": 12.13, "currency": "USD", "is_surge": false } ], "next_cursor": null, "has_more": false } ``` Each row is machine-seconds (`unit` is always `"second"`). Surge and non-surge usage of the same app and machine type are returned as **separate rows** (`is_surge`), so sum across them for a per-app total. Time-series `bucket` timestamps are returned in the `timezone` you request (ISO 8601 with offset, e.g. `2025-01-15T00:00:00-05:00`), which also controls how usage is grouped. `cost` is already net of your discounts. ## Logs Query paginated logs with powerful label filters, time ranges, and search keywords. Stream live logs that match the provided filters using Server-Sent Events. ## Analytics Query time-bucketed metrics across all inbound traffic to your apps — request counts, error-type breakdown (startup, connection, timeout, runtime), latency percentiles (p25 through p99), cold boot metrics, and total billable duration. Ideal for exporting to your own observability tools. ## Metrics Read the current queue backlog for your serverless applications. Export app metrics (runners, queue size, concurrent requests, throughput, and latency) in Prometheus format for custom dashboards and monitoring. # Platform APIs for Storage Source: https://fal.ai/docs/api-reference/platform-apis/for-storage Manage access control, signed URLs, and lifecycle settings for fal CDN files The **fal Platform APIs** for Storage provide programmatic control over files stored on the fal CDN, including: * **File ACLs** - Read and replace the Access Control List of a CDN file to make it public, restrict it, or grant access to specific users * **Signed URLs** - Mint time-limited URLs that grant temporary access to access-restricted files (valid up to 7 days) * **Account storage settings** - Configure account-wide defaults for newly uploaded files, including auto-expiration and the initial ACL ## Available Operations The Platform APIs provide the following endpoints for Storage: Retrieve the Access Control List currently applied to a fal CDN file Replace the Access Control List of a fal CDN file with a default decision and optional per-user rules Create a signed URL that grants temporary access to a file regardless of its ACL Read the account-level lifecycle settings applied to newly uploaded files Replace the account-level defaults for auto-expiration and the initial ACL of new uploads ## Access Control Lists A file ACL is composed of a **default decision** plus optional **per-user rules** that override the default: * `allow` - access is granted * `forbid` - access is denied (the file returns an error) * `hide` - access is denied and the file is treated as if it does not exist Setting `default` to `allow` with no rules makes a file public. Using `forbid` or `hide` restricts the file to only the users named in the rules. Rules that reference users who do not exist are dropped. The response always reflects the ACL actually applied, so verify it contains the rules you sent. ## Authentication All Storage endpoints require authentication. Include your API key in the `Authorization` header: ``` Authorization: Key YOUR_API_KEY ``` Permissions are split by capability: | Operation | Required permission | | ---------------------------- | ------------------------ | | Get file ACL / Sign file URL | `assets:read` | | Set file ACL | `assets:write` | | Get storage settings | `account:settings:read` | | Update storage settings | `account:settings:write` | # Platform APIs for Workflows Source: https://fal.ai/docs/api-reference/platform-apis/for-workflows Programmatic access to workflow creation, metadata, listing, and details The **fal Platform APIs** provide programmatic access to workflow management for the authenticated user, including: * **List workflows** - Paginated list of your workflows with optional search and filtering * **Get workflow details** - Retrieve a specific workflow by owner and name, including its full definition * **Create workflow** - Create a new workflow owned by the authenticated user ## Available Operations The Platform APIs provide the following endpoints for Workflows: List workflows for the authenticated user with optional search and filtering by endpoint Get detailed information about a specific workflow, including its full definition Create a new workflow owned by the authenticated user ## Authentication All Workflows endpoints require authentication. Include your API key in the `Authorization` header: ``` Authorization: Key YOUR_API_KEY ``` List workflows returns only workflows owned by the authenticated user. Get workflow details requires access to the workflow (e.g., it is yours or public). Creating a workflow adds it to the authenticated user's namespace. These APIs are for **platform management** of Workflows (creating, listing, and reading). To run workflows, use the [Model APIs](/docs/model-apis) or workflow execution endpoints. # Introduction to Platform APIs Source: https://fal.ai/docs/api-reference/platform-apis/index Platform APIs provide programmatic access to platform resources including model metadata, usage tracking, analytics, and fal Assets.