我正在尝试遵循此API文档,该文档指出要传递API密钥和json对象,尽管它始终返回错误
它说请求的内容必须是JSON对象,而成分必须是数组。
我不知道即时通讯做错了还是API损坏了。我确实得到了另一个API调用来工作,但营养成分却没有。
curl -d @food.json -H "Content-Type: application/json" "https://api.edamam.com/api/food-database/nutrients?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
{
"yield": 1,
"ingredients": [
{
"quantity": 1,
"measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_unit",
"foodURI": "http://www.edaman.com/ontologies/edamam.owl#Food_USDABR_45039390"
}
]
}
在我的代码中,这就是我得到的:
let json: [String: Any] = [
"ingredients": ["quantity":1,
"measureURI":"http://www.edamam.com/ontologies/edamam.owl#Measure_pound",
"foodURI" : "http://www.edaman.com/ontologies/edamam.owl#Food_USDABR_45039390"]]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// Nutrition API
let app_id = "51fkkff"
let app_key = "6503a430030768824iidkos03d431d94"
let urlString = String(format: "https://api.edamam.com/api/food-database/nutrients?app_id=%@&app_key=%@", app_id, app_key)
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
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)
}
}
task.resume()
错误消息:["message": Entity could not be parsed, "error": bad_request]
答案 0 :(得分:1)
将其与API文档进行比较时,我看到两个需要修复的错误:
yield
字段。我刚刚使用此JSON对象进行了测试,效果很好:
let json: [String: Any] = [
"yield": 1,
"ingredients": [
[
"quantity": 1,
"measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_pound",
"foodURI": "http://www.edamam.com/ontologies/edamam.owl#Food_USDABR_45039390"
]
]
]