How to perform a curl request in swift?

Viewed 14579

I am trying to use an external API, which has an API request that is like the following. I am used to requests with just one url, but what do I do with the "H" and the "d" arguments? Should I include them in my url or

$ 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"}'

Currently I have the following code, but where do I place the API key and the document id in this code?

@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)
        }


}
1 Answers

This is an example of how you can translate the curl command into 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()
Related