iosswiftswift5airtable

Send data to Airtables through a POST request with a json body


Im trying to send data to Airtables using its REST APIs based on the documentation. The part Im stuck is adding the parameters. It throws me an error saying "Invalid request: parameter validation failed. Check your request data".

The Curl according to the doc as bellow.

enter image description here

My partially done code as bellow.

    let table_name = "Diet%20Plan"
    let base_id = "appmrzybooFj9mFVF"
    let token = "SomeID"
      
      // prepare json data
    let json: [String: String] = ["Food Type": "Minseee",
                                     "Person Name": "Rabiit Con"]
    
    // create the url with URL
    let url = URL(string: "https://api.airtable.com/v0/\(base_id)/\(table_name)")! // change server url accordingly

    let jsonData = try? JSONSerialization.data(withJSONObject: json)

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")
    
    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) //Code after Successfull POST Request
        }
    }

    task.resume()
}

Solution

  • From your code, request body seems to be made like:

    {"Person Name":"Rabiit Con","Food Type":"Minseee"}
    

    What it needs to be sending is:

    "fields": {
       "Person Name":"Rabiit Con",
       "Food Type":"Minseee"
    }
    

    Try

    let json: [String: Any] = ["fields": ["Food Type": "Minseee",
                                          "Person Name": "Rabiit Con"]]
    
    let jsonData = try? JSONSerialization.data(withJSONObject: json)