我正在尝试使用一个外部API,该API具有如下所示的API请求。我习惯于仅使用一个URL进行请求,但是使用“ H”和“ d”参数该怎么办?我应该将它们包含在我的网址中还是
$ curl -X POST https://api.lucidtech.ai/v0/receipts \
-H 'x-api-key: <your api key>' \
-H 'Content-Type: application/json' \
-d '{"documentId": "a50920e1-214b-4c46-9137-2c03f96aad56"}'
当前我有以下代码,但是我应该在该代码中的何处放置API密钥和文档ID?
@IBAction func getScannedData(_ sender: Any){
guard let url = URL(string: "https://api.lucidtech.ai/v0/receipts") else {return}
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response{
print(response)
}
}
答案 0 :(得分:2)
这是一个如何将curl
命令转换为URLRequest
的示例:
guard let url = URL(string: "https://api.lucidtech.ai/v0/receipts"),
let payload = "{\"documentId\": \"a50920e1-214b-4c46-9137-2c03f96aad56\"}".data(using: .utf8) else
{
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("your_api_key", forHTTPHeaderField: "x-api-key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = payload
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }
if let str = String(data: data, encoding: .utf8) {
print(str)
}
}.resume()