1

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
            }
        }
    ]
}
Matt Le Fleur
  • 2,708
  • 29
  • 40
Atta Ahmed
  • 71
  • 7
  • Tip: Since you have a working curl, did you know that Alamofire can print its requests as curl? Then you can compare and spot issue. See https://stackoverflow.com/questions/53637437/alamofire-with-d/53637821#53637821 Then you can see what parameter you put https://github.com/Alamofire/Alamofire/blob/master/Source/Session.swift#L307 and change them – Larme Jul 13 '20 at 15:30

1 Answers1

2

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.

Frankenstein
  • 15,732
  • 4
  • 22
  • 47