> ## Documentation Index
> Fetch the complete documentation index at: https://docs.flashduty.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 导入告警规则

> 从 JSON 数组导入一条或多条告警规则，返回每条规则的导入结果（成功或失败）。

## 限制说明

| 项目   | 说明                         |
| ---- | -------------------------- |
| 速率限制 | 每个账户 **20 次/分钟**；**2 次/秒** |
| 权限要求 | **告警规则管理**（`monit`）        |

## 使用说明

* 请求体为规则导出对象的 JSON 数组（与 `POST /monit/rule/export` 输出兼容）。
* 每个对象必须包含 `folder_id`、`ds_type` 以及 `ds_list` 或 `ds_ids` 之一。
* 部分规则可能失败（如名称重复），请检查每条结果的状态。
* 每次调用都会记录到账户审计日志，请不要把敏感信息放在请求字段中。


## OpenAPI

````yaml /api-reference/monitors.openapi.zh.json post /monit/rule/import
openapi: 3.1.0
info:
  title: Flashduty 开放 API
  description: >-
    Flashduty 事件管理平台的公开 HTTP API —— 覆盖故障、通知模板、协作空间、值班排班、监控、RUM、以及平台管理。每次调用都需在
    query 中携带 `app_key`，该 key 在 Flashduty 控制台 账户 → APP Key 中签发。所有响应使用统一结构：成功时为
    `{ request_id, data }`，失败时为 `{ request_id, error }`。
  version: 1.0.0
servers:
  - url: https://api.flashcat.cloud
    description: Flashduty Open API
security:
  - AppKeyAuth: []
tags:
  - name: Monitors/告警规则
    description: 创建、管理和导出监控告警规则，查询规则统计和审计历史。
  - name: Monitors/告警数据源
    description: 管理监控告警规则用于查询指标的数据源。
  - name: Monitors/规则集
    description: 管理 Monitors 规则仓库中的共享规则集，规则集可在账户内或公开共享。
  - name: Monitors/诊断分析
    description: Flashduty AI SRE 使用的诊断与查询接口——数据源即席查询、日志/指标诊断,以及监控对象侧的工具调用。
  - name: Monitors/通用工具
    description: 监控服务开通及数据预览工具。
paths:
  /monit/rule/import:
    post:
      tags:
        - Monitors/告警规则
      summary: 导入告警规则
      description: 从 JSON 数组导入一条或多条告警规则，返回每条规则的导入结果（成功或失败）。
      operationId: monit-rule-write-import
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RuleImportRequest'
            example:
              - folder_id: 100
                name: CPU 过高
                ds_type: prometheus
                ds_list:
                  - prometheus*
                enabled: true
                cron_pattern: '* * * * *'
                rule_configs:
                  queries:
                    - name: A
                      expr: avg(cpu_usage_idle) < 10
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/SuccessEnvelope'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/RuleImportResponse'
              example:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                data:
                  - name: CPU 过高
                    message: ''
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/ServerError'
components:
  schemas:
    RuleImportRequest:
      type: array
      description: 要导入的告警规则导出对象数组。
      items:
        $ref: '#/components/schemas/AlertRule'
    SuccessEnvelope:
      type: object
      description: >-
        成功响应结构。2xx 响应中 `request_id` 标识本次调用（同时出现在 `Flashcat-Request-Id`
        响应头中），`data` 为接口业务 payload。失败响应使用不同结构，参见 `ErrorResponse`。
      properties:
        request_id:
          type: string
          description: 本次请求的唯一 ID，也会在 Flashcat-Request-Id 响应头中返回。反馈问题时请一并附上。
          example: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
        data:
          description: 每个接口自己的业务 payload，详见各接口的 200 响应 schema。
      required:
        - request_id
        - data
    RuleImportResponse:
      type: array
      items:
        $ref: '#/components/schemas/NameMessage'
      description: 每条规则的导入结果。
    AlertRule:
      type: object
      description: 完整的告警规则配置。
      properties:
        id:
          type: integer
          format: uint64
        account_id:
          type: integer
          format: uint64
        folder_id:
          type: integer
          format: uint64
          description: 规则所属文件夹。
        name:
          type: string
          description: 规则名称。
        labels:
          type: object
          additionalProperties:
            type: string
          description: 自定义标签。
        ds_type:
          type: string
          description: 数据源类型。
        ds_list:
          type: array
          items:
            type: string
          description: 数据源名称模式（支持通配符）。
        ds_ids:
          type: array
          items:
            type: integer
            format: uint64
          description: 具体数据源 ID 列表。
        enabled:
          type: boolean
        debug_log_enabled:
          type: boolean
        rule_configs:
          $ref: '#/components/schemas/RuleConfigs'
        cron_pattern:
          type: string
          description: 5 字段 cron 调度。不允许以 `CRON_TZ=` 或 `TZ=` 开头，时区请填写到 `timezone` 字段。
        timezone:
          type: string
          description: >-
            告警规则执行时区，决定 cron 调度与生效时间窗口的解释方式。仅接受 IANA 时区名（如
            `Asia/Shanghai`、`UTC`、`Europe/London`）；不接受 `Local`、`UTC+8`、`CST`
            等简写或偏移量。留空时按 `Asia/Shanghai` 处理。
          default: Asia/Shanghai
        delay_seconds:
          type: integer
        enabled_times:
          type: array
          description: 规则生效的时间窗口。
          items:
            type: object
            properties:
              days:
                type: array
                items:
                  type: integer
                description: 星期几（0=周日）。
              stime:
                type: string
                description: 开始时间，如 `09:00`。
              etime:
                type: string
                description: 结束时间，如 `18:00`。
        annotations:
          type: object
          additionalProperties:
            type: string
        description_type:
          type: string
          enum:
            - text
            - markdown
        description:
          type: string
        channel_ids:
          type: array
          items:
            type: integer
            format: uint64
          description: 告警发送到的协作空间 ID 列表。
        repeat_interval:
          type: integer
          format: int64
          description: 通知重复间隔（秒）。
        repeat_total:
          type: integer
          format: int64
          description: 最大重复通知次数。
        creator_id:
          type: integer
          format: uint64
        creator_name:
          type: string
        updater_id:
          type: integer
          format: uint64
        updater_name:
          type: string
        created_at:
          type: integer
          format: int64
        updated_at:
          type: integer
          format: int64
    NameMessage:
      type: object
      description: 批量规则操作中，单条规则的处理结果。
      required:
        - name
        - message
      properties:
        name:
          type: string
          description: 规则名称。
        message:
          type: string
          description: 成功时为空，失败时为错误信息。
    ErrorResponse:
      type: object
      description: 错误响应结构。`error` 必填，`data` 不存在。
      properties:
        request_id:
          type: string
          example: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
        error:
          $ref: '#/components/schemas/DutyError'
      required:
        - request_id
        - error
    RuleConfigs:
      type: object
      description: 规则评估配置。
      properties:
        queries:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
                description: 查询标识符（字母，如 `A`）。`R` 为保留名称，不可使用。
              expr:
                type: string
                description: 查询表达式。
              label_fields:
                type: array
                items:
                  type: string
              value_fields:
                type: array
                items:
                  type: string
              args:
                type: object
                additionalProperties:
                  type: string
        relate_queries:
          type: array
          description: 可选的辅助查询，其结果作为上下文附加到告警事件中。每项须有唯一的 `name`（不与任何 query 名称重复）且 `expr` 非空。
          items:
            type: object
            properties:
              name:
                type: string
                description: 辅助查询标识符。
              expr:
                type: string
                description: 查询表达式。
              args:
                type: object
                additionalProperties:
                  type: string
        check_threshold:
          type: object
          description: 阈值检查配置。
          properties:
            enabled:
              type: boolean
            alerting_check_times:
              type: integer
            recovery_check_times:
              type: integer
            push_recovery_event:
              type: boolean
            critical:
              type: string
            warning:
              type: string
            info:
              type: string
            recovery:
              type: object
              properties:
                mode:
                  type: string
                  enum:
                    - invert
                    - threshold
                    - ql
                condition:
                  type: string
        check_anydata:
          type: object
          description: 有数据检查配置。查询返回任意数据行时触发告警。
          properties:
            enabled:
              type: boolean
            alerting_check_times:
              type: integer
            recovery_check_times:
              type: integer
            push_recovery_event:
              type: boolean
            severity:
              type: string
              enum:
                - Critical
                - Warning
                - Info
            recovery:
              type: object
              description: 有数据检查的恢复条件。省略或 `mode` 为空时按 `nodata` 处理。
              properties:
                mode:
                  type: string
                  enum:
                    - nodata
                    - ql
                  description: >-
                    `nodata` = 查询无数据时恢复；`ql` = `condition` 表达式为真时恢复。`mode` 为
                    `ql` 时，仅允许单个查询（`name=A`）。
                condition:
                  type: string
                  description: 恢复表达式，`mode` 为 `ql` 时必填。
                args:
                  type: object
                  additionalProperties:
                    type: string
        check_nodata:
          type: object
          description: 无数据检查配置。
          properties:
            enabled:
              type: boolean
            alerting_check_times:
              type: integer
            recovery_check_times:
              type: integer
            push_recovery_event:
              type: boolean
            severity:
              type: string
              enum:
                - Critical
                - Warning
                - Info
            resolve_timeout:
              type: integer
              description: 自动恢复等待时间（秒）。
    DutyError:
      type: object
      description: 响应结构中的错误 payload，仅在非 2xx 响应时出现。
      properties:
        code:
          $ref: '#/components/schemas/ErrorCode'
        message:
          type: string
          description: 用户可读的错误描述，语言会跟随调用方的 Accept-Language。可能包含字段名、ID 等请求上下文。
          example: The specified parameter template_id is not valid.
      required:
        - code
        - message
    ErrorCode:
      type: string
      description: >-
        Flashduty 错误码枚举。每个失败响应的 `error.code` 都是下列稳定值之一，HTTP 状态码仅作参考。


        | 错误码 | HTTP | 含义 |

        |---|---|---|

        | `OK` | 200 | 保留值，正常错误响应不会返回。 |

        | `InvalidParameter` | 400 | 必填参数缺失或未通过校验。 |

        | `BadRequest` | 400 | 通用的 400 错误，通常是请求本身不合法。 |

        | `InvalidContentType` | 400 | 请求头 `Content-Type` 不是 `application/json`。
        |

        | `ResourceNotFound` | 400 | 目标资源不存在。注意 HTTP 状态码是 400 而非 404（历史设计）。 |

        | `NoLicense` | 400 | 功能需要有效授权，但未找到可用的 license。 |

        | `ReferenceExist` | 400 | 该资源仍被其他实体引用，无法删除。 |

        | `Unauthorized` | 401 | `app_key` 缺失、无效或已过期。 |

        | `BalanceNotEnough` | 402 | 账户余额不足，无法执行需要计费的操作。 |

        | `AccessDenied` | 403 | 身份认证通过，但 RBAC 权限不足以执行该操作。 |

        | `RouteNotFound` | 404 | 请求的 URL 路径不是已知路由。 |

        | `MethodNotAllowed` | 405 | 当前路径不接受所使用的 HTTP 方法。 |

        | `UndonedOrderExist` | 409 | 账户存在未完成的订单，请稍后重试。 |

        | `RequestLocked` | 423 | 因连续失败被临时锁定。 |

        | `EntityTooLarge` | 413 | 请求体超过允许的最大长度。 |

        | `RequestTooFrequently` | 429 | 命中限流（全局、账户级或集成级）。 |

        | `RequestVerifyRequired` | 428 | 操作需要二次验证码，但未提供。 |

        | `DangerousOperation` | 428 | 危险操作，需要进行 MFA 验证。 |

        | `InternalError` | 500 | 服务端未预期错误。反馈问题请附上 `request_id`。 |

        | `ServiceUnavailable` | 503 | 后端依赖不可用，请稍后重试。 |
      enum:
        - OK
        - InvalidParameter
        - BadRequest
        - InvalidContentType
        - ResourceNotFound
        - NoLicense
        - ReferenceExist
        - Unauthorized
        - BalanceNotEnough
        - AccessDenied
        - RouteNotFound
        - MethodNotAllowed
        - UndonedOrderExist
        - RequestLocked
        - EntityTooLarge
        - RequestTooFrequently
        - RequestVerifyRequired
        - DangerousOperation
        - InternalError
        - ServiceUnavailable
      x-enumDescriptions:
        OK: 保留值，正常错误响应不会返回。
        InvalidParameter: 必填参数缺失或未通过校验。
        BadRequest: 通用的 400 错误，通常是请求本身不合法。
        InvalidContentType: 请求头 `Content-Type` 不是 `application/json`。
        ResourceNotFound: 目标资源不存在。注意 HTTP 状态码是 400 而非 404（历史设计）。
        NoLicense: 功能需要有效授权，但未找到可用的 license。
        ReferenceExist: 该资源仍被其他实体引用，无法删除。
        Unauthorized: '`app_key` 缺失、无效或已过期。'
        BalanceNotEnough: 账户余额不足，无法执行需要计费的操作。
        AccessDenied: 身份认证通过，但 RBAC 权限不足以执行该操作。
        RouteNotFound: 请求的 URL 路径不是已知路由。
        MethodNotAllowed: 当前路径不接受所使用的 HTTP 方法。
        UndonedOrderExist: 账户存在未完成的订单，请稍后重试。
        RequestLocked: 因连续失败被临时锁定。
        EntityTooLarge: 请求体超过允许的最大长度。
        RequestTooFrequently: 命中限流（全局、账户级或集成级）。
        RequestVerifyRequired: 操作需要二次验证码，但未提供。
        DangerousOperation: 危险操作，需要进行 MFA 验证。
        InternalError: 服务端未预期错误。反馈问题请附上 `request_id`。
        ServiceUnavailable: 后端依赖不可用，请稍后重试。
      example: InvalidParameter
  responses:
    BadRequest:
      description: 请求非法 — 通常是参数缺失或格式不正确。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missingParameter:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: InvalidParameter
                  message: The specified parameter is not valid.
    Unauthorized:
      description: app_key 缺失或无效。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missingAppKey:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: Unauthorized
                  message: You are unauthorized.
    TooManyRequests:
      description: 命中限流。可能是全局 API 限流、账户级限流或集成级限流。限流按账户聚合。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            rateLimited:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: RequestTooFrequently
                  message: Request too frequently.
    ServerError:
      description: 服务端未预期错误。反馈问题时请携带 request_id。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            internal:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: InternalError
                  message: >-
                    We encountered an internal error, and it has been reported.
                    Please try again later.
  securitySchemes:
    AppKeyAuth:
      type: apiKey
      in: query
      name: app_key
      description: >-
        在 Flashduty 控制台 账户 → APP Key 中签发的 app_key。调用任何公开 API
        时都必须携带。它等同于所属账户的身份凭证，请妥善保管。

````