This is a companion discussion topic for the original entry at https://www.raywenderlich.com/870225-server-side-swift-with-vapor/lessons/5
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/870225-server-side-swift-with-vapor/lessons/5
In this challenge I get the following error when creating the user-info route:
Value of type 'Int' required for key 'age'.
Swift 5.2
Vapor 4
The issue goes away if I make the age property a String, but I don’t think that is the right approach here?
// ...
router.post("user-info") { req -> String in
let data = try req.content.syncDecode(UserData.self)
return "Hello \(data.name), you are \(data.age)"
}
// ...
struct UserData: Content {
let name: String
let age: Int
}
It would seem this is an input issue, where Vapor is not typecasting the posted value to Int, as HTTP is not type-aware and everything is treated as a string?
@mikebronner how are you sending the request? In JSON there’s a difference between
"age": 99
and
"age": "99"
The second one provides the String, whereas your code is expecting an Int. Yes they’re essentially the same, but that’s what Codable
looks for and why you’re getting an error
1 Like
Tim, you’re absolutely right. I forgot to check my API request. Thanks!!
1 Like