swiftalamofire-request

How can you send a nested object in the body of an Alamofire API request?


I tried to use Alamofire to make an API request like this:

let param = ["id":"xy", "products":[["quantity":2, "product":["id":123]]]]

Alamofire.request(url, method: .post,
                   parameters: param, encoding: URLEncoding.default, 
                      headers: ["Accept": "application/json", "Content-Type": "application/json"]).responseJSON ..

I received this response:

message = "Unexpected token i in JSON at position 0";
statusCode = 400;

I also tried to make a request like this:

request.httpBody = try! JSONSerialization.data(withJSONObject: param)

I tried to perform the following request manually to mark sure that it was working fine:

curl -X POST http://url -d'{"id":"xy", "products" [{"quantity":2,"product":{"id":123}}]}' -H'Content-Type: application/json'

And as desired, it gave me this response:

{
    "id":"xy",
    "products":[
        {
            "quantity":2,
            "product":{
                "id":123
            }
        }
    ]
}

Solution

  • You need to send the request as application/json so use JSONEncoding.default as encoding parameter.

    Alamofire.request( url, method: .post , parameters: param, encoding: JSONEncoding.default , headers: ["Accept": "application/json",
                          "Content-Type": "application/json"])
    

    Add-on: Also, you can loose the Content-Type from the header parameters. AF takes care of that for you.