{
  "openapi": "3.0.3",
  "info": {
    "title": "MySQLBot Services API",
    "version": "1.0.0",
    "description": "Programmatic API for MySQLBot's verified-answer & document services: verified/cited research briefs, competitor analyses, and structured data extraction from documents. Authenticate with an API key in the X-Api-Key header. Order lifecycle: create_order -> poll status -> fetch deliverable (returned inline). Human-readable guide: https://mysqlbot.com/pages/public/serviceApiGuide.php",
    "contact": { "name": "MySQLBot", "url": "https://mysqlbot.com/pages/public/?page=contact" }
  },
  "servers": [ { "url": "https://mysqlbot.com" } ],
  "security": [ { "ApiKeyAuth": [] } ],
  "paths": {
    "/pages/public/serviceApi.php": {
      "post": {
        "operationId": "postAction",
        "summary": "create_order (needs X-Api-Key) or register (no auth)",
        "description": "POST actions. create_order (X-Api-Key) creates + queues an order; a prepaid key debits its balance (402 insufficient_balance) and idempotency_key makes retries safe. (The website's 'Clean up my Excel file' mode — tidy an uploaded workbook IN PLACE, keeping its worksheets/layout/formatting — is WEB-ONLY: it operates on your original binary .xlsx, which the API's text-only source_docs cannot carry; API extraction with deliverable_format=xlsx still returns the extracted data as an Excel workbook.) quote (free, nothing charged or stored) takes the same body as create_order and returns the exact price + code-only suitability checks + a measured time estimate. preview (free, rate-capped) runs the real engine on a small sample: extraction returns the first rows (optionally in the requested output_locale / amount_style + date_style, echoed back); briefs web-verify two sample claims from your document. delete_data (body: ref) PERMANENTLY erases the order's document, result and notes — the web's 'Delete my data' — idempotent ({deleted, already, deleted_at}); only a bare non-personal payment record is kept for tax; no undo. register (NO auth) mints a new prepaid key with a zero balance, returning api_key + top_up_url inline. The remaining actions are ACCOUNT/TEAM MANAGEMENT for a key attached to a team account, gated by the key's member permissions (mirrors the web control panel): invite_member/remove_member (can_manage_members), set_permissions/rename_account (owner only), create_key/revoke_key (can_manage_keys), set_display_name/set_password (self). See the human guide (serviceApiGuide.php) for each action's body fields. Auth is OPTIONAL at the operation level only because register needs none; every other action requires X-Api-Key.",
        "security": [ { "ApiKeyAuth": [] }, {} ],
        "parameters": [
          { "name": "action", "in": "query", "required": true, "schema": { "type": "string", "enum": ["create_order", "quote", "preview", "delete_data", "register", "invite_member", "remove_member", "set_permissions", "create_key", "revoke_key", "rename_account", "set_display_name", "set_password"] } }
        ],
        "requestBody": {
          "required": false,
          "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/CreateOrderRequest" }, { "$ref": "#/components/schemas/RegisterRequest" } ] } } }
        },
        "responses": {
          "200": { "description": "create_order → an order (or idempotent duplicate); register → a new prepaid key.", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/CreateOrderResponse" }, { "$ref": "#/components/schemas/RegisterResponse" } ] } } } },
          "400": { "description": "invalid_service_type | empty_request | extraction_requires_source_docs | request_too_long (request text over 20000 chars, data.max = 20000) | invalid_email (register) | invalid_json (register: non-empty body that is not a JSON object)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "401": { "description": "invalid_api_key (create_order)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "402": { "description": "insufficient_balance — prepaid key balance too low; data has balance, required, currency, top_up_url", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "403": { "description": "no_permission | not_an_account_key | key_member_not_resolved (management actions)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "409": { "description": "already_a_member_somewhere (invite_member)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "405": { "description": "use_POST_for_create_order | use_POST_for_register | use_POST_for_delete_data", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "413": { "description": "source_docs_too_long (data.max = 20000000) | brief_source_too_long (briefs: source over 10000000 chars, the full-verification ceiling — split the document)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "429": { "description": "rate_limited | daily_order_cap_reached | provision_rate_limited (register) | preview_capped / rig_busy (preview — previews run at HIGH queue priority and slot between a long job's chunks; on rig_busy honour the Retry-After header, and data carries retry_after_s + eta_low_s/eta_high_s, null when no honest estimate exists)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "500": { "description": "create_failed | provision_failed | delete_failed | server_error — transient; retry with backoff", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "503": { "description": "service_price_unconfigured | service temporarily unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } }
        }
      },
      "get": {
        "operationId": "getAction",
        "summary": "Order status / deliverable / prepaid balance",
        "description": "GET actions (all require X-Api-Key). status → order state (poll until done) + download_url when done; deliverable → finished output inline (text) + download_url (tokenised one-GET file download — the .xlsx workbook for Excel orders, a .zip bundle when delivery notes ship alongside); balance → the key's prepaid balance + top_up_url; a key only sees orders it created. preview_eta (&service_type=...) → free read-only wait estimate for the free preview: data.state (idle|soon|busy|unknown), data.eta_low_s/eta_high_s (seconds, null when no honest estimate exists), data.queue_ahead — ask before spending a preview call while a long job runs. Account/team reads for an account-attached key (see guide §8): account → who am I + permissions; list_members (can_manage_members) → team roster; list_keys (can_manage_keys) → the account's keys; list_orders → account orders (a member without can_see_all_orders sees only their own).",
        "parameters": [
          { "name": "action", "in": "query", "required": true, "schema": { "type": "string", "enum": ["status", "deliverable", "balance", "account", "list_members", "list_keys", "list_orders", "preview_eta"] } },
          { "name": "ref", "in": "query", "required": false, "description": "The order_ref (required for status/deliverable; omit for the others).", "schema": { "type": "string" } },
          { "name": "limit", "in": "query", "required": false, "description": "list_orders: max rows (<=200, default 50).", "schema": { "type": "integer" } }
        ],
        "responses": {
          "200": { "description": "status → order state; deliverable → finished output; balance → prepaid balance.", "content": { "application/json": { "schema": { "oneOf": [ { "$ref": "#/components/schemas/StatusResponse" }, { "$ref": "#/components/schemas/DeliverableResponse" }, { "$ref": "#/components/schemas/BalanceResponse" } ] } } } },
          "400": { "description": "missing_ref | unknown_action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "401": { "description": "invalid_api_key", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "403": { "description": "no_permission | not_an_account_key (account/team reads)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "404": { "description": "order_not_found (wrong ref, or not this key's order)", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "409": { "description": "not_ready (data.status) | order_refunded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "410": { "description": "deliverable_expired — the 30-day retention window has passed and the deliverable was automatically deleted (privacy policy) | data_deleted — the order's document and result were permanently erased (delete_data or the web 'Delete my data')", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "429": { "description": "rate_limited", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
          "500": { "description": "server_error — transient; retry with backoff", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": { "type": "apiKey", "in": "header", "name": "X-Api-Key", "description": "An sk_-prefixed API key. Self-provision one instantly via POST ?action=register (no auth, prepaid), create one in the client portal (Team -> Create key), or request one from the operator." }
    },
    "schemas": {
      "Envelope": {
        "type": "object",
        "properties": {
          "ok": { "type": "boolean" },
          "error": { "type": "string", "description": "Machine-readable error code (empty on success)." },
          "data": { "type": "object", "additionalProperties": true }
        },
        "required": ["ok", "error", "data"]
      },
      "CreateOrderRequest": {
        "type": "object",
        "required": ["service_type", "request"],
        "properties": {
          "service_type": { "type": "string", "enum": ["research_brief", "competitor_brief", "extraction"], "description": "The service to run." },
          "request": { "type": "string", "description": "The research question / competitor set / extraction instructions." },
          "source_docs": { "type": "string", "description": "Document TEXT to extract from. Required for extraction. Text only — to extract from a spreadsheet, send its contents as CSV text (the web form's Excel upload does this conversion automatically; the API does not accept binary uploads). Max 20000000 chars (~20 MB); large docs are processed in chunks. Extraction is priced by document size (larger documents cost more); the create response returns the charged amount." },
          "source_docs_base64": { "type": "string", "description": "Base64 of a text file, decoded server-side. Use instead of source_docs." },
          "title": { "type": "string", "description": "Optional short label." },
          "priority": { "type": "string", "enum": ["low", "standard", "high"], "default": "standard" },
          "deliverable_format": { "type": "string", "enum": ["markdown", "csv", "json", "xlsx", "text"], "description": "markdown (default for briefs) | csv (default for extraction) | json (extraction only -> a JSON array) | xlsx (extraction only: delivers an Excel workbook; the deliverable field stays CSV text and the .xlsx binary is fetched via the download_url returned by status/deliverable) | text." },
          "output_locale": { "type": "string", "description": "Extraction output format: a composite <amount>_<date> token (e.g. plain_uk, symbol_iso) or raw. Legacy country codes (gb, us, ...) accepted. Alternative: send amount_style + date_style." },
          "amount_style": { "type": "string", "enum": ["asis", "plain", "symbol"], "description": "Extraction amount axis (alternative to output_locale): asis = as in the source; plain = strip symbol/grouping to a bare number; symbol = ensure symbol + comma grouping. Values are never converted." },
          "date_style": { "type": "string", "enum": ["asis", "uk", "us", "iso"], "description": "Extraction date axis (alternative to output_locale): asis | uk (DD/MM/YYYY) | us (MM/DD/YYYY) | iso (YYYY-MM-DD)." },
          "output_options": { "type": "object", "description": "Extraction with csv or xlsx output (json orders carry no options): optional clean-up passes as an object of option keys (e.g. {\"dedup\":\"1\",\"round\":\"2\",\"delim\":\"semicolon\"}). Keys: empty (blank|na), ws (1), neg (minus|brackets), delim (semicolon|tab), quoteall (1), header (snake|title), boolstd (yesno|truefalse), postcode (1), nameord (firstlast), phone (intl|national), timestd (h24|h12), dedup (1), mergecont (1), round (0|1|2|3). Unknown keys ignored." },
          "idempotency_key": { "type": "string", "description": "Optional. Makes retries safe: the same key returns the same order instead of re-billing." }
        }
      },
      "CreateOrderResponse": {
        "type": "object",
        "properties": {
          "ok": { "type": "boolean", "example": true },
          "error": { "type": "string" },
          "data": {
            "type": "object",
            "properties": {
              "order_ref": { "type": "string", "example": "SO-XXXX" },
              "status": { "type": "string", "example": "pending" },
              "service_type": { "type": "string" },
              "amount": { "type": "number" },
              "currency": { "type": "string", "example": "GBP" },
              "billing": { "type": "string" },
              "duplicate": { "type": "boolean", "description": "Present and true if an idempotent duplicate was returned." },
              "note": { "type": "string" },
              "output_locale": { "type": "string", "description": "Echoed extraction output-format token (e.g. plain_uk, symbol_iso, raw)." },
              "output_format": { "type": "string", "description": "Human label for the output format (amount × date axes)." },
              "amount_style": { "type": "string", "description": "Echoed amount axis: asis | plain | symbol." },
              "date_style": { "type": "string", "description": "Echoed date axis: asis | uk | us | iso." }
            }
          }
        }
      },
      "StatusResponse": {
        "type": "object",
        "properties": {
          "ok": { "type": "boolean" },
          "error": { "type": "string" },
          "data": {
            "type": "object",
            "properties": {
              "order_ref": { "type": "string" },
              "status": { "type": "string", "enum": ["pending", "processing", "done", "failed", "cancelled"] },
              "service_type": { "type": "string" },
              "amount": { "type": "number" },
              "currency": { "type": "string" },
              "payment_status": { "type": "string" },
              "tokens": { "type": "integer" },
              "verify_outcome": { "type": "string", "nullable": true },
              "error": { "type": "string" },
              "created_at": { "type": "string" },
              "completed_at": { "type": "string" },
              "deliverable_ready": { "type": "boolean" },
              "download_url": { "type": "string", "description": "Tokenised URL: one plain GET downloads the finished file exactly as the web delivers it (.xlsx for Excel orders, .zip when delivery notes ship alongside, else the plain .csv/.md/.txt/.json). Empty string until deliverable_ready." },
              "data_deleted": { "type": "boolean", "description": "True once the order's document and result have been permanently erased (via delete_data or the web's Delete my data)." },
              "delete_url": { "type": "string", "description": "Tokenised URL of the human 'Delete my data' confirm page. Empty once deleted. For programmatic erasure use POST ?action=delete_data." },
              "output_locale": { "type": "string", "description": "Echoed extraction output-format token (e.g. plain_uk, symbol_iso, raw)." },
              "output_format": { "type": "string", "description": "Human label for the output format (amount × date axes)." },
              "amount_style": { "type": "string", "description": "Echoed amount axis: asis | plain | symbol." },
              "date_style": { "type": "string", "description": "Echoed date axis: asis | uk | us | iso." }
            }
          }
        }
      },
      "DeliverableResponse": {
        "type": "object",
        "properties": {
          "ok": { "type": "boolean" },
          "error": { "type": "string" },
          "data": {
            "type": "object",
            "properties": {
              "order_ref": { "type": "string" },
              "status": { "type": "string", "example": "done" },
              "service_type": { "type": "string" },
              "deliverable_format": { "type": "string" },
              "deliverable": { "type": "string", "description": "The full finished output (markdown / CSV text / JSON string per deliverable_format)." },
              "download_url": { "type": "string", "description": "Tokenised URL: one plain GET downloads the finished file (.xlsx for Excel orders, .zip when delivery notes ship alongside, else the plain text file)." },
              "delete_url": { "type": "string", "description": "Tokenised URL of the human 'Delete my data' confirm page. For programmatic erasure use POST ?action=delete_data." },
              "output_locale": { "type": "string", "description": "Echoed extraction output-format token (e.g. plain_uk, symbol_iso, raw)." },
              "output_format": { "type": "string", "description": "Human label for the output format (amount × date axes)." },
              "amount_style": { "type": "string", "description": "Echoed amount axis: asis | plain | symbol." },
              "date_style": { "type": "string", "description": "Echoed date axis: asis | uk | us | iso." }
            }
          }
        }
      },
      "RegisterRequest": {
        "type": "object",
        "description": "Body for POST ?action=register (no auth). All fields optional; a non-empty body that is not a JSON object is rejected with 400 invalid_json.",
        "properties": {
          "name": { "type": "string", "description": "A label for the key (shown in your key listing). 'label' is accepted as an alias.", "maxLength": 120 },
          "label": { "type": "string", "description": "Alias for name.", "maxLength": 120 },
          "email": { "type": "string", "format": "email", "description": "Contact address for receipts/notifications. Invalid addresses are rejected with 400 invalid_email." }
        }
      },
      "RegisterResponse": {
        "type": "object",
        "description": "Response to POST ?action=register (no auth): a freshly provisioned prepaid key.",
        "properties": {
          "ok": { "type": "boolean", "example": true },
          "error": { "type": "string" },
          "data": {
            "type": "object",
            "properties": {
              "api_key": { "type": "string", "description": "The sk_ key — shown ONCE, store it now.", "example": "sk_..." },
              "key_prefix": { "type": "string" },
              "billing": { "type": "string", "example": "prepaid" },
              "balance": { "type": "number", "example": 0 },
              "currency": { "type": "string", "example": "GBP" },
              "top_up_url": { "type": "string", "description": "Open this (or hand it to the human paying) to fund the key via PayPal." },
              "guide_url": { "type": "string" },
              "note": { "type": "string" }
            }
          }
        }
      },
      "BalanceResponse": {
        "type": "object",
        "description": "Response to GET ?action=balance: the authenticated key's prepaid balance.",
        "properties": {
          "ok": { "type": "boolean" },
          "error": { "type": "string" },
          "data": {
            "type": "object",
            "properties": {
              "billing": { "type": "string", "enum": ["prepaid", "account"] },
              "balance": { "type": "number" },
              "currency": { "type": "string" },
              "top_up_url": { "type": "string", "description": "Present (non-empty) for a prepaid key; empty for an account-billed key." }
            }
          }
        }
      }
    }
  }
}
