Berry
Berry

Reputation: 2298

How to handle PUT HTTP request in Vapor?

The only way I've found to update a record in Vapor is this:

drop.get("update") { request in

  guard var first = try Acronym.query().first(),
    let long = request.data["long"]?.string else {
    throw Abort.badRequest
  }
  first.long = long
  try first.save()
  return first

}

However it's not a very RESTful way of doing it since it's performing a GET request with a parameter instead of a PUT request.

How does one perform a PUT request in Vapor?

Upvotes: 0

Views: 750

Answers (2)

Quver
Quver

Reputation: 1418

drop.put("update") { request in
  guard var first = try Acronym.query().first(),
    let long = request.data["long"]?.string else {
    throw Abort.badRequest
  }

  first.long = long
  try first.save()

  return first
}

Upvotes: 0

Berry
Berry

Reputation: 2298

As it turns out, performing PUT, as well as other HTTP methods are as simple as changing .get() or .post() to .put() or any other HTTP methods.

As for my question, to create a PUT function in Vapor, just simply add a .put method that takes an Int (Or String, or any data type you'd like), and accept a JSON (Or whatever format you'd like), and simply update like it's a POST request.

Upvotes: 2

Related Questions