【问题标题】:Api request in SwiftSwift 中的 API 请求
【发布时间】:2017-11-23 14:44:08
【问题描述】:

我想为应用使用配方 API。我已经注册并获得了一个 API 的密钥。但是,我不知道将密钥放在 URL 中的哪个位置,因此我可以将其粘贴到浏览器中并获取 JSON 响应。 这是 Curl 请求的示例

$response = Unirest\Request::get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1",
  array(
    "X-Mashape-Key" => "KEY",
    "X-Mashape-Host" => "spoonacular-recipe-food-nutrition-v1.p.mashape.com"
  )
);

这是我在搜索 URL 时得到的:

{  
   "message":"Missing Mashape application key. Go to http:\/\/docs.mashape.com\/api-keys to learn how to get your API application key."
}

如果有人知道如何使用密钥或其他方式创建完整的 URL 以在 Swift 中获取 Json 响应,我们将不胜感激。 谢谢

【问题讨论】:

标签: json swift api


【解决方案1】:

如果您想在 Swift 中调用 API,我建议您使用此处的 Alamofire 库:https://github.com/Alamofire/Alamofire

为了对 API 调用进行身份验证,您必须按照他们的文档了解他们希望您如何进行身份验证。一些服务没有身份验证,而另一些使用一次性使用令牌,一些使用通过请求标头传递的 API 密钥。看起来此 API 调用需要通过请求标头传递密钥和主机。使用 Alamofire,请求看起来像这样:

let headers: HTTPHeaders = [
    "X-Mashape-Key": "KEY",
    "X-Mashape-Host": "spoonacular-recipe-food-nutrition-v1.p.mashape.com"
]

Alamofire.request("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1", headers: headers).responseJSON { response in
    debugPrint(response)
}

如果您想测试 API 调用而不事先在应用程序中对请求进行编码,我建议您下载一个名为 Postman 的应用程序。这将允许您测试 API 并查看它们的响应,从而在您的 swift 应用中为您提供帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多