通过带有JSON主体的POST请求将数据发送到Airables

uqjltbpv  于 2022-10-23  发布在  Swift
关注(0)|答案(1)|浏览(202)

我正在尝试使用基于文档的REST API将数据发送到Airables。我被卡住的部分是添加参数。它向我抛出一个错误消息:“无效请求:参数验证失败。请检查您的请求数据”。
卷发根据文件如下所示。

我的部分代码如下所示。

let table_name = "Diet%20Plan"
    let base_id = "appmrzybooFj9mFVF"
    let token = "SomeID"

      // prepare json data
    let json: [String: String] = ["Food Type": "Minseee",
                                     "Person Name": "Rabiit Con"]

    // create the url with URL
    let url = URL(string: "https://api.airtable.com/v0/\(base_id)/\(table_name)")! // change server url accordingly

    let jsonData = try? JSONSerialization.data(withJSONObject: json)

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")

    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON) //Code after Successfull POST Request
        }
    }

    task.resume()
}
mnowg1ta

mnowg1ta1#

从您的代码来看,请求正文似乎是这样的:

{"Person Name":"Rabiit Con","Food Type":"Minseee"}

它需要发送的是:

"fields": {
   "Person Name":"Rabiit Con",
   "Food Type":"Minseee"
}

尝试

let json: [String: Any] = ["fields": ["Food Type": "Minseee",
                                      "Person Name": "Rabiit Con"]]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

相关问题