{
  "openapi": "3.0.1",
  "info": {
    "title": "UN COMTRADE — Import/Export by Country & HS Code",
    "description": "Search UN COMTRADE for global import/export trade data by country, commodity HS code, and year. Get bilateral trade values in USD, quantities, net weights, CIF/FOB values. Supports 200+ countries with free preview or authenticated API.",
    "version": "2.9",
    "x-build-id": "k7jJBAHVdgkhe3cNG"
  },
  "servers": [
    {
      "url": "https://api.apify.com/v2"
    }
  ],
  "paths": {
    "/acts/ryanclinton~un-comtrade-search/run-sync-get-dataset-items": {
      "post": {
        "operationId": "run-sync-get-dataset-items-ryanclinton-un-comtrade-search",
        "x-openai-isConsequential": false,
        "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
        "tags": [
          "Run Actor"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/inputSchema"
              }
            }
          }
        },
        "parameters": [
          {
            "name": "token",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Enter your Apify token here"
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          }
        }
      }
    },
    "/acts/ryanclinton~un-comtrade-search/runs": {
      "post": {
        "operationId": "runs-sync-ryanclinton-un-comtrade-search",
        "x-openai-isConsequential": false,
        "summary": "Executes an Actor and returns information about the initiated run in response.",
        "tags": [
          "Run Actor"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/inputSchema"
              }
            }
          }
        },
        "parameters": [
          {
            "name": "token",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Enter your Apify token here"
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/runsResponseSchema"
                }
              }
            }
          }
        }
      }
    },
    "/acts/ryanclinton~un-comtrade-search/run-sync": {
      "post": {
        "operationId": "run-sync-ryanclinton-un-comtrade-search",
        "x-openai-isConsequential": false,
        "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
        "tags": [
          "Run Actor"
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/inputSchema"
              }
            }
          }
        },
        "parameters": [
          {
            "name": "token",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Enter your Apify token here"
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "inputSchema": {
        "type": "object",
        "properties": {
          "analysisMode": {
            "title": "Analysis Mode (one-click preset)",
            "enum": [
              "raw",
              "market-scan",
              "supplier-risk",
              "bilateral-audit",
              "tariff-impact",
              "portfolio-monitor",
              "executive-brief",
              "monitor"
            ],
            "type": "string",
            "description": "Pre-configured analysis workflow. Each mode auto-enables the right analytics and defaults. Use 'raw' for direct API access, 'monitor' for scheduled watchlist runs.",
            "default": "raw"
          },
          "outputMode": {
            "title": "Output Mode",
            "enum": [
              "standard",
              "decision"
            ],
            "type": "string",
            "description": "'standard' emits all record types (trade, insight, alert, recommendation, summary, etc.) for maximum flexibility. 'decision' emits a single consolidated DecisionRecord with headline, top3Actions, keyRisks, keyOpportunities, whatChanged, why, and confidence — perfect for AI agents, dashboards, and 'give me the answer' workflows.",
            "default": "standard"
          },
          "reporter": {
            "title": "Reporter Country",
            "type": "string",
            "description": "Reporting country name, ISO2/ISO3 code, or UN M49 numeric code. Accepts 'USA', 'US', 'America', 'Germany', 'DEU', '276', etc. Leave empty to query all reporters. Use 'reporters' (plural) for benchmark mode."
          },
          "reporters": {
            "title": "Reporters (benchmark mode)",
            "type": "array",
            "description": "Array of reporter countries for cross-country benchmark mode. Example: compare EU members' semiconductor imports: [\"Germany\", \"France\", \"Netherlands\", \"Italy\"]. When set, the actor runs one query per reporter and returns ranked benchmark records.",
            "items": {
              "type": "string"
            }
          },
          "partner": {
            "title": "Partner Country",
            "type": "string",
            "description": "Partner country name, ISO2/ISO3 code, or UN M49 numeric code. Leave empty to include all trading partners."
          },
          "partners": {
            "title": "Partners (benchmark mode)",
            "type": "array",
            "description": "Array of partner countries for multi-partner benchmark mode.",
            "items": {
              "type": "string"
            }
          },
          "commodity": {
            "title": "Commodity / HS Code",
            "type": "string",
            "description": "HS commodity code (e.g. '0101' live horses, '2701' coal, '2709' crude petroleum, '8703' cars). Text search supported ('sugar' → HS 1701). Use 'TOTAL' for aggregate, or 'AG2'/'AG4'/'AG6' for hierarchy rollups. Leave empty for 'TOTAL'."
          },
          "commodities": {
            "title": "Multiple Commodities",
            "type": "array",
            "description": "Array of HS codes for multi-commodity portfolio queries. Example: `[\"8542\", \"8471\", \"3002\"]`. Overrides 'commodity' when set.",
            "items": {
              "type": "string"
            }
          },
          "commodityPack": {
            "title": "Strategic Commodity Pack",
            "enum": [
              "none",
              "semiconductors",
              "rare-earths",
              "ev-supply-chain",
              "batteries",
              "pharma-inputs",
              "fossil-fuels",
              "critical-minerals",
              "agricultural-staples"
            ],
            "type": "string",
            "description": "Preset HS code bundles for common sector-level analysis. Overrides 'commodity' and 'commodities' when set.",
            "default": "none"
          },
          "tradeFlow": {
            "title": "Trade Flow",
            "enum": [
              "Import",
              "Export",
              "Re-Import",
              "Re-Export",
              "All"
            ],
            "type": "string",
            "description": "Direction of trade flow. Set to 'All' to enable trade balance computation.",
            "default": "All"
          },
          "frequency": {
            "title": "Data Frequency",
            "enum": [
              "A",
              "M"
            ],
            "type": "string",
            "description": "Annual (A) or Monthly (M) trade data. Monthly mode pulls the last N months and computes rolling averages and trend slope. Available for most reporters since ~2010.",
            "default": "A"
          },
          "lookbackPeriods": {
            "title": "Lookback Periods",
            "minimum": 1,
            "maximum": 60,
            "type": "integer",
            "description": "Number of consecutive periods to query in monthly mode (e.g. 12 = last 12 months). Ignored in annual mode (use 'yoyYears' instead).",
            "default": 12
          },
          "year": {
            "title": "Year",
            "type": "string",
            "description": "Trade year (e.g. '2023'). Comma-separated for multiple years. In monthly mode, YYYYMM format is also accepted. Leave empty for 2 years before current (most recent typically available). Ignored when yoyYears > 1 — the actor auto-computes the window."
          },
          "subscriptionKey": {
            "title": "UN COMTRADE API Subscription Key",
            "type": "string",
            "description": "Optional subscription key for the authenticated endpoint (up to 250,000 records per query). Without a key, the free preview endpoint is used (limited to 500 records). Get a key at https://comtradeplus.un.org/."
          },
          "maxResults": {
            "title": "Max Results",
            "minimum": 1,
            "maximum": 250000,
            "type": "integer",
            "description": "Maximum number of records per query. Without a subscription key, hard-capped at 500 by UN COMTRADE's free endpoint. With a subscription key, the ceiling is 250,000.",
            "default": 100
          },
          "includeUnitValue": {
            "title": "Unit value (price/kg, price/unit)",
            "type": "boolean",
            "description": "Adds derived pricePerKg and pricePerUnit fields. Helps detect HS-code misclassification and flag unusually cheap/expensive shipments. Auto-enabled by market-scan, bilateral-audit, tariff-impact, portfolio-monitor, executive-brief modes."
          },
          "includeTradeBalance": {
            "title": "Compute trade balance (exports − imports)",
            "type": "boolean",
            "description": "Computes net bilateral trade balance per reporter-partner-commodity-year. Requires tradeFlow = 'All'. Auto-enabled by bilateral-audit, tariff-impact, executive-brief modes."
          },
          "topPartners": {
            "title": "Top N trading partners",
            "minimum": 0,
            "maximum": 50,
            "type": "integer",
            "description": "Returns ranked top-N partners by trade value with share %. Best with partner field empty. Auto-enabled by market-scan (10), supplier-risk (15), portfolio-monitor (5), executive-brief (10) modes."
          },
          "includeHHI": {
            "title": "Compute supply-chain concentration (HHI)",
            "type": "boolean",
            "description": "Herfindahl-Hirschman Index across trading partners with concentration level tag and top-1/3/5 share. Auto-enabled by market-scan, supplier-risk, portfolio-monitor, executive-brief, monitor modes."
          },
          "yoyYears": {
            "title": "YoY trend window (years)",
            "minimum": 1,
            "maximum": 10,
            "type": "integer",
            "description": "Number of consecutive years to query for trend analysis. Returns YoY growth %, CAGR, and trend direction records. Auto-set by analysisMode (market-scan: 3, supplier-risk: 5, bilateral-audit: 3, tariff-impact: 5, portfolio-monitor: 3, executive-brief: 5, monitor: 3)."
          },
          "detectAnomalies": {
            "title": "Detect anomalies (z-score > 2)",
            "type": "boolean",
            "description": "Flags records where latest value deviates >2 standard deviations from the historical mean. Requires yoyYears >= 3. Auto-enabled by supplier-risk, bilateral-audit, tariff-impact, portfolio-monitor, executive-brief, monitor modes."
          },
          "includeMirrorCheck": {
            "title": "Mirror data discrepancy check",
            "type": "boolean",
            "description": "Compares reporter values against partner mirror data. Flags potential misinvoicing or reporting gaps. Requires single reporter AND single partner. Auto-enabled by bilateral-audit mode."
          },
          "includeTariffs": {
            "title": "Enrich with WITS tariff data",
            "type": "boolean",
            "description": "Fetches applied tariff rates from World Bank WITS. Capped at 100 records. Free public API. Auto-enabled by supplier-risk, tariff-impact, executive-brief modes."
          },
          "includeMacroContext": {
            "title": "Include macro context (GDP, inflation)",
            "type": "boolean",
            "description": "Attaches GDP, GDP growth, inflation, population, and trade-as-%-of-GDP from World Bank Open Data. Auto-enabled by tariff-impact, executive-brief modes."
          },
          "includeInsights": {
            "title": "Generate plain-English insights",
            "type": "boolean",
            "description": "Runs the insights engine over computed analytics and emits 'insight' records with claim, headline, whyItMatters, evidence, severity, and a recommended next query. Turns raw data into decision support. Auto-enabled by all non-raw modes."
          },
          "includeQualityScore": {
            "title": "Compute per-series quality + confidence scores",
            "type": "boolean",
            "description": "Emits 'quality' records with dataQualityScore (0-100), confidenceScore (0-1), confidenceLevel, decisionReadiness, and qualityFlags. Helps you trust the analysis. Auto-enabled by most modes."
          },
          "includeAlerts": {
            "title": "Trigger threshold-based alerts",
            "type": "boolean",
            "description": "Emits structured 'alert' records when analytics cross thresholds: concentration-jump, share-shift, mirror-gap, yoy-drop, yoy-spike, anomaly-detected. Plug-and-play with Zapier/Make/Slack. Auto-enabled by supplier-risk, bilateral-audit, tariff-impact, portfolio-monitor, executive-brief, monitor modes."
          },
          "alertThresholds": {
            "title": "Alert Thresholds",
            "type": "object",
            "description": "Override default alert thresholds. Defaults: shareShiftPp=10, mirrorDiscrepancyPct=30, hhiJump=500, yoyDropPct=20, yoySpikePct=50, anomalyZScore=2."
          },
          "emitAlertsOnly": {
            "title": "Emit alerts only (monitoring mode)",
            "type": "boolean",
            "description": "When true, skip raw trade records and summaries — output only alerts, insights, quality, and narrative. Use for scheduled monitoring jobs that should only return 'what changed'. Auto-enabled by monitor mode."
          },
          "includeNarrative": {
            "title": "Generate executive narrative summary",
            "type": "boolean",
            "description": "Emits a 'summary' record with oneParagraphSummary, fiveBulletBrief, topFindings, top3Actions, and confidenceDrivers. Usable in emails, reports, and Slack messages without modification. Auto-enabled by executive-brief mode."
          },
          "includeCausalAnalysis": {
            "title": "Causal analysis — answer WHY",
            "type": "boolean",
            "description": "Rule-based correlation engine that ranks likely drivers of observed trade changes (tariff change, GDP alignment, partner shift). Emits 'cause' records with ranked drivers and confidence. Requires multi-year data. Auto-enabled by supplier-risk, executive-brief modes."
          },
          "includeRecommendations": {
            "title": "Actionable recommendations",
            "type": "boolean",
            "description": "Template-based recommendations with type (diversification / risk-mitigation / opportunity / investigation), severity, confidence, and suggestedAction. Auto-enabled by supplier-risk, portfolio-monitor, executive-brief, monitor modes."
          },
          "simulate": {
            "title": "Scenario simulation (what-if)",
            "type": "object",
            "description": "Run a what-if simulation. Fields: tariffChangePct (e.g. 10 for +10pp tariff), gdpChangePct, demandShockPct, targetPartner. Uses historical elasticity for directional estimates. Returns 'scenario' records with heavy caveats — NOT a forecast."
          },
          "includePortfolioInsights": {
            "title": "Portfolio-level insights (when >1 commodity)",
            "type": "boolean",
            "description": "Aggregates across the commodity pack or commodities[] array. Returns a 'portfolio-insight' record with avg HHI, median growth, overall trend, and risk level. Auto-enabled by portfolio-monitor, executive-brief modes."
          },
          "includeGraphEdges": {
            "title": "Trade graph edges (for Neo4j / network viz)",
            "type": "boolean",
            "description": "Emits 'graph-edge' records (source, target, commodity, weight) ready to ingest into Neo4j, NetworkX, or any graph visualization tool."
          },
          "baseline": {
            "title": "Baseline period (for delta comparison)",
            "type": "string",
            "description": "Baseline period for delta-vs-baseline comparison. Single year ('2020') or range ('2020-2022'). Emits 'delta' records comparing the latest year against the baseline mean."
          },
          "watchlistId": {
            "title": "Watchlist ID (for scheduled monitoring)",
            "type": "string",
            "description": "Stable identifier for this monitoring configuration. When set with includeChangeDetection, the actor saves per-run metrics in a named KV store and emits 'change-summary' records describing what changed since last run. Perfect for scheduled Apify runs."
          },
          "includeChangeDetection": {
            "title": "Cross-run change detection",
            "type": "boolean",
            "description": "Compare current run against the previous run for this watchlistId. Emits 'change-summary' records with new/resolved alerts, changed metrics. Requires watchlistId. Auto-enabled by monitor mode."
          },
          "includeReasoning": {
            "title": "Include reasoning traces on insights",
            "type": "boolean",
            "description": "Adds a 'reasoning' array to each insight record with plain-English audit trail of how the insight was computed. Makes insights auditable and LLM-friendly. Auto-enabled by supplier-risk, portfolio-monitor, executive-brief modes."
          }
        }
      },
      "runsResponseSchema": {
        "type": "object",
        "properties": {
          "data": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string"
              },
              "actId": {
                "type": "string"
              },
              "userId": {
                "type": "string"
              },
              "startedAt": {
                "type": "string",
                "format": "date-time",
                "example": "2025-01-08T00:00:00.000Z"
              },
              "finishedAt": {
                "type": "string",
                "format": "date-time",
                "example": "2025-01-08T00:00:00.000Z"
              },
              "status": {
                "type": "string",
                "example": "READY"
              },
              "meta": {
                "type": "object",
                "properties": {
                  "origin": {
                    "type": "string",
                    "example": "API"
                  },
                  "userAgent": {
                    "type": "string"
                  }
                }
              },
              "stats": {
                "type": "object",
                "properties": {
                  "inputBodyLen": {
                    "type": "integer",
                    "example": 2000
                  },
                  "rebootCount": {
                    "type": "integer",
                    "example": 0
                  },
                  "restartCount": {
                    "type": "integer",
                    "example": 0
                  },
                  "resurrectCount": {
                    "type": "integer",
                    "example": 0
                  },
                  "computeUnits": {
                    "type": "integer",
                    "example": 0
                  }
                }
              },
              "options": {
                "type": "object",
                "properties": {
                  "build": {
                    "type": "string",
                    "example": "latest"
                  },
                  "timeoutSecs": {
                    "type": "integer",
                    "example": 300
                  },
                  "memoryMbytes": {
                    "type": "integer",
                    "example": 1024
                  },
                  "diskMbytes": {
                    "type": "integer",
                    "example": 2048
                  }
                }
              },
              "buildId": {
                "type": "string"
              },
              "defaultKeyValueStoreId": {
                "type": "string"
              },
              "defaultDatasetId": {
                "type": "string"
              },
              "defaultRequestQueueId": {
                "type": "string"
              },
              "buildNumber": {
                "type": "string",
                "example": "1.0.0"
              },
              "containerUrl": {
                "type": "string"
              },
              "usage": {
                "type": "object",
                "properties": {
                  "ACTOR_COMPUTE_UNITS": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATASET_READS": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATASET_WRITES": {
                    "type": "integer",
                    "example": 0
                  },
                  "KEY_VALUE_STORE_READS": {
                    "type": "integer",
                    "example": 0
                  },
                  "KEY_VALUE_STORE_WRITES": {
                    "type": "integer",
                    "example": 1
                  },
                  "KEY_VALUE_STORE_LISTS": {
                    "type": "integer",
                    "example": 0
                  },
                  "REQUEST_QUEUE_READS": {
                    "type": "integer",
                    "example": 0
                  },
                  "REQUEST_QUEUE_WRITES": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATA_TRANSFER_INTERNAL_GBYTES": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATA_TRANSFER_EXTERNAL_GBYTES": {
                    "type": "integer",
                    "example": 0
                  },
                  "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                    "type": "integer",
                    "example": 0
                  },
                  "PROXY_SERPS": {
                    "type": "integer",
                    "example": 0
                  }
                }
              },
              "usageTotalUsd": {
                "type": "number",
                "example": 0.00005
              },
              "usageUsd": {
                "type": "object",
                "properties": {
                  "ACTOR_COMPUTE_UNITS": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATASET_READS": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATASET_WRITES": {
                    "type": "integer",
                    "example": 0
                  },
                  "KEY_VALUE_STORE_READS": {
                    "type": "integer",
                    "example": 0
                  },
                  "KEY_VALUE_STORE_WRITES": {
                    "type": "number",
                    "example": 0.00005
                  },
                  "KEY_VALUE_STORE_LISTS": {
                    "type": "integer",
                    "example": 0
                  },
                  "REQUEST_QUEUE_READS": {
                    "type": "integer",
                    "example": 0
                  },
                  "REQUEST_QUEUE_WRITES": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATA_TRANSFER_INTERNAL_GBYTES": {
                    "type": "integer",
                    "example": 0
                  },
                  "DATA_TRANSFER_EXTERNAL_GBYTES": {
                    "type": "integer",
                    "example": 0
                  },
                  "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                    "type": "integer",
                    "example": 0
                  },
                  "PROXY_SERPS": {
                    "type": "integer",
                    "example": 0
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}