Search code examples
jsonpostswift2alamofire

Swift 2 - POST requests don't get parameters added


Following up to a question someone asked on the Alamofire github issues that never got answered because I want the answer as well.

Doing a simple request with GET adds my parameters nicely, but doing a POST doesn't.

let parameters = ["foo": "bar"]

Alamofire.request(.POST, "url", parameters: parameters)
.responseJSON { request, response, json, error in
  print("request: \(request)")
}

returns

request: Optional(<NSMutableURLRequest: 0x7f9864109cb0> { URL: https://api.github.com/repos/BasThomas/junk/issues })
 while

let parameters = ["foo": "bar"]

Alamofire.request(.GET, "url", parameters: parameters)
.responseJSON { request, response, json, error in
  print("request: \(request)")
}

returns

request: Optional(<NSMutableURLRequest: 0x7f9ef07ef0f0> { URL: https://api.github.com/repos/BasThomas/junk/issues?foo=bar })

Solution

  • The parameters of a POST are added to the request body, not to the URL. This is due to the common conventions between GET and POST.

    Custom Parameter Encoding

    If you need to append them to the URL (sounds like you do), then I'd suggest you take a look at the .Custom ParameterEncoding type. That will allow you to follow the same logic as the encode method, but append the parameters however you like.

    Also, the methods inside the ParameterEncoding enum have now all been made public so you'll have access to the query parameter splitting and escaping.