Trying to send data into my postgreSQL database using Vapor and Swift.
Here is example code (Swift Struct as Request Body)
struct ToDoResponseModel: Codable {
var id: Int
var Name: String
var isComplete: Bool
}
let url = URL(string: "http://localhost:8080/todos")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Header
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let newTodoItem = ToDoResponseModel(id: 300, Name: "Urgent task 2", isComplete: true)
do {
let jsonData = try JSONEncoder().encode(newTodoItem)
request.httpBody = jsonData
}catch let jsonErr{
print(jsonErr)
}
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
return
}
guard let data = data else {return}
do {
let todoItemModel = try JSONDecoder().decode(ToDoResponseModel.self, from: data)
print("Response data:\n \(todoItemModel)")
print("todoItemModel Name: \(todoItemModel.Name)")
print("todoItemModel id: \(todoItemModel.id )")
} catch let jsonErr {
print(jsonErr)
}
}
task.resume()
But I faced the next error:
keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))
Error fixed on this line:
let todoItemModel = try JSONDecoder().decode(ToDoResponseModel.self, from: data)
and Vapor sends me :
[ ERROR ] DecodingError.keyNotFound: Value required for key 'IsComplete'. (ErrorMiddleware.swift:26)