Posting a String array to an API via JSON body in Swift

Viewed 61

I am trying to upload a string array to the Edamam API that uses the data from my local database. For the API, I need to post an array of strings with a label "ingr" so that it would recognize it. I should be able to enter the "\(mass) grams \(name)" of each ingredient and get a response that would analyze the macronutrients of said ingredient. The code I'm using:

API Config:

func getData(strURL: String, dictParam: Dictionary<String, Any>, completion: @escaping(Dictionary<String, AnyObject>)->()) {

        var request = URLRequest(url: URL(string: strURL)!)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject: dictParam, options: [])
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let session = URLSession.shared
        let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
            print(response!)
            do {
                let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
                print(json)
                completion(json)
            } catch {
                print("error")
            }
        })
        task.resume()
    }

API call:

let dictParams = ["ingr":["100 grams apple"]] as Dictionary<String, Any>
        APICalling.shared.getData(strURL: baseURL, dictParam: dictParams) { (response) in
                 action()
            }
        }

When using the Rested app, I can upload as many ingredients as I want and will get the correctly formatted response, everything is dandy. However, when I try to implement the code in my app, it prints "error":conflict. Any ideas how I can properly implement the API call?

1 Answers

Found a fix to the issue. Added some headers to my request, everything works fine now.

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("*/*", forHTTPHeaderField: "Accept")
        request.addValue("no-cache", forHTTPHeaderField: "Cache-Control")
        request.addValue("api.edamam.com", forHTTPHeaderField: "Host")
        request.addValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.addValue("keep-alive", forHTTPHeaderField: "Connection")
Related