POST using Alamofire 5

GET | POST

By Will Braynen


In a nutshell:

// `POST /yourendpoint`
session.request(
  "https://yourbackend.com/yourendpoint",   
  method: .post,  
  parameters: payload, // `Encodable` (or `Codable`) struct
  encoder: JSONParameterEncoder.default)

That is how you would POST to the server the contents of payload as JSON in the http body. This is using Alamofire 5 (beta 7). More fully:

/// The network session you would likely share between all your
/// network calls.
let session = Alamofire.Session()

/// This can also be a `Codable`, although `Encodable` is all 
/// you need if you are never receiving this from the backend
/// and only sending it.
struct Payload: Encodable {
  let username: String
  let password: String
}

/// An `Encodable` object from which to construct the http body.
let payload = Payload(
  username: "ada",
  password: "o2LAJH12Y2!kq1dA")

// `POST /yourendpoint`
session.request(
  "https://yourbackend.com/yourendpoint", 
  method: .post, 
  parameters: payload, // `Encodable` (or `Codable`) struct
  encoder: JSONParameterEncoder.default)
// `.validate` is an optional convenience, which classifies as
// `.failure(error)` any responses that have an http status code
// other than what you specify.
//
// Also, if you are expecting a JSON response from the endpoint
// and want to decode that response, you could use 
// `.responseDecodable` instead of `.response`.
request.validate(codes: [200, 201, 202]).response(
  completionHandler: { result in
    // Print the curl for your request.
    debugPrint(request)

    // Print the result.
    print(result)
})

// Unlike Alamofire 4, Alamofire 5 creates the request task
// asynchronously, so the request will likely not be created 
// at this point, so printing it here will just give you nil, 
// which is why we are printing it inside the completion handler
// instead.
debugPrint(request)

That’s it. Happy coding!