Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift 3 posting json parameter to api

Tags:

json

swift3

I need to pass the following json to this function so Shopify Api can understand the submission.

Every time I execute this code, I get an error message that there is a missing required parameter. Obviously, I am unable to create the correct variable format and pass it to server.

Shopify API is expecting the following json to be passed via POST

{
    "customer": {
        "first_name": "Steve",
        "last_name": "Lastnameson",
        "email": "[email protected]",
        "verified_email": true,
        "addresses": [
            {
                "address1": "123 Oak St",
                "city": "Ottawa",
                "province": "ON",
                "phone": "555-1212",
                "zip": "123 ABC",
                "last_name": "Lastnameson",
                "first_name": "Mother",
                "country": "CA"
            }
        ]
    }
}

Here is my posting code:

let customer = [
    "customer": [
        "first_name": "Steve",
        "last_name": "Lastnameson",
        "email": "[email protected]",
        "verified_email": "true",
        "addresses": [
            [
                "address1": "123 Oak St",
                "city": "Ottawa",
                "province": "ON",
                "phone": "555-1212",
                "zip": "123 ABC",
                "last_name": "Lastnameson",
                "first_name": "Mother",
                "country": "CA",
            ],
        ],
    ],
] as [String: Any]

var request = URLRequest(url: URL(string: shopUrl + "/admin/customers.json")!)
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: customer, options: [])

URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
    if error != nil {
        print(error)
    } else {
        do {
            guard let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else { return }

            guard let errors = json?["errors"] as? [[String: Any]] else { return }
                if errors.count > 0 {
                    // show error
                    return
                } else {
                    // show confirmation
                }
            }
        }
    }).resume()
like image 503
Hamid Avatar asked Sep 25 '16 12:09

Hamid


1 Answers

The request needs to have the content type declared. Add:

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
like image 96
David Chu Avatar answered Nov 03 '22 09:11

David Chu