CSAllenISDClassroom / sudokuserver-acid-dragons-1

sudokuserver-acid-dragons-1 created by GitHub Classroom
1 stars 1 forks source link

PUT request gives response of "Ensure that you pass an integer in the request body" despite correct passing of value in HTTP request #34

Closed konjo0567 closed 3 years ago

konjo0567 commented 3 years ago

How I got this issue:

First. I spooled up a server of the current version of this code under the URL: "https://codermerlin.com/vapor/jean-martin-vaneskahian"

Second, I successfully executed a POST request against the API to get an ID for the game. the ID was : "5771082358054111728".

Third, I got the ID and formed the PUT URL, as "https://codermerlin.com/vapor/jean-martin-vaneskahian/games/5771082358054111728/cells/0/0". I also referenced this website: "https://johncodeos.com/how-to-make-post-get-update-and-delete-requests-with-urlsession-using-swift/" for the adding of the HTML body, to store the JSON input.

Finally I executed the code and it gave me the response of "Ensure that you pass an integer in the request body".

The code used to send this PUT request is listed below. (code is codey-looking) (Please tell me if you find any errors that is on my end)

import Foundation
import FoundationNetworking

//Creating a structure to pass as a value 
struct UploadData: Codable {
    let value : Int
}
let uploadDataModel = UploadData(value: 1)

let jsonData = try? JSONEncoder().encode(uploadDataModel)

// Form the request
var request = URLRequest(url: URL(string: "https://codermerlin.com/vapor/jean-martin-vaneskahian/games/5771082358054111728/cells/0/0")!)
request.httpMethod = "PUT"
request.httpBody = jsonData

// Execute synchronously (uses extension in code below)
let (data, response, error) = URLSession.shared.syncRequest(with: request)
if let data = data,
   let string = String(data: data, encoding: .utf8) {
    print(string)
} else if let error = error {
    print("Error: \(error)")
} else {
    print("An unexpected error occurred.")
}

// Reference: https://stackoverflow.com/questions/26784315/can-i-somehow-do-a-synchronous-http-request-via-nsurlsession-in-swift
extension URLSession {
    func syncRequest(with request: URLRequest) -> (Data?, URLResponse?, Error?) {
        var data: Data?
        var response: URLResponse?
        var error: Error?

        let dispatchGroup = DispatchGroup()
        let task = dataTask(with: request) {
            data = $0
            response = $1
            error = $2
            dispatchGroup.leave()
        }
        dispatchGroup.enter()
        task.resume()
        dispatchGroup.wait()

        return (data, response, error)
    }
}
AmyPham1893 commented 3 years ago

Try git pull for the new version. Response if it still have error.