You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复AWS Amplify Mock API的ValidationException错误

问题:AWS Amplify本地测试时DynamoDB PutItem缺少主键值

按照AWS Workshop指引操作,点击Play按钮后触发错误:ValidationException: One of the required keys was not given a value,本地DynamoDB日志显示PutItem操作的key字段为空。已尝试添加/移除Schema中ID字段的必填标记(!),问题未解决。

错误日志

AppSync Mock endpoint is running at http://192.168.20.3:20002
Error while executing Local DynamoDB
{
    "version": "2018-05-29",
    "operation": "PutItem",
    "attributeValues": {
        "type": {
            "S": "post"
        },
        "content": {
            "S": "test"
        },
        "timestamp": {
            "N": "1668425585"
        },
        "owner": {
            "S": "7d8ca528-4931-4254-9273-ea5ee853f271::user1"
        },
        "__typename": {
            "S": "Post"
        }
    },
    "condition": {
        "expression": "attribute_not_exists(#id)",
        "expressionNames": {
            "#id": "id"
        }
    },
    "key": {}
}
ValidationException: One of the required keys was not given a value

Schema文件

input AMPLIFY {
  globalAuthRule: AuthRule = { allow: public }
} # FOR TESTING ONLY!
type Post
  @model(
    mutations: { create: "createPost", delete: "deletePost", update: null }
    timestamps: null
    subscriptions: { level: public }
  )
  @auth(
    rules: [
      {
        allow: owner
        ownerField: "owner"
        provider: userPools
        operations: [read, create, delete]
      }
      { allow: private, provider: userPools, operations: [read] }
    ]
  ) {
  type: String! # always set to 'post'. used in the SortByTimestamp GSI
  id: ID!
  content: String!
  owner: String
  timestamp: Int!
}

解决建议

  • 手动传入ID值测试:调用createPost mutation时,手动生成一个UUID作为id参数传入,确认是否能正常写入DynamoDB。
  • 检查@model主键配置:确认@model指令未自定义primaryKey参数覆盖默认主键(默认以id为主键),如果有自定义配置,确保主键字段被正确传入。
  • 更新Amplify CLI版本:运行npm install -g @aws-amplify/cli更新到最新版本,然后重启本地mock环境(amplify mock api restart),旧版本可能存在自动生成ID的bug。
  • 重新生成API配置:执行amplify api gql-compile重新编译GraphQL Schema,再重启mock服务,确保自动生成的mutation输入类型包含id字段。
  • 验证条件表达式逻辑:日志中的条件表达式attribute_not_exists(#id)依赖id字段,确保mutation请求中确实包含id,避免因字段缺失导致条件判断异常。

内容的提问来源于stack exchange,提问作者nanospeck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:40:42