Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift POST request sends an empty body

Tags:

json

rest

ios

swift

Here's the code:

func makePOSTCall(endpoint: String, languageName: String) {
    guard let url = URL(string: endpoint) else {
        print("Could not create URL.")
        return
    }

    let requestLang: [String: Any] = ["name": languageName]
    let requestBody = try? JSONSerialization.data(withJSONObject: requestLang)

    var urlRequest = URLRequest(url: url)
    urlRequest.httpBody = requestBody
    urlRequest.httpMethod = "POST"
    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest) {

        data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }

        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }

    }
    task.resume()
}

This sends a {"name": "Go"} JSON dictionary to Flask. Flask is supposed to append the language name to an array and return the full array in the response. Now, this works when I send the request manually, so it's not Flask's error. But when I send the above from iOS, I get request.json == None in the flask console. Clearly, I'm sending an empty body, but I shouldn't be. Any idea where I went wrong?

I call the function as

@IBAction func pressedMakePOSTCall(_ sender: UIButton) {

    makePOSTCall(endpoint: "http://127.0.0.1:5000/lang", languageName: "Go")

}

I tried adding a trailing slash, just get a 404 in the console. The only question similar to mine that I've found is this: How to make HTTP Post request with JSON body in Swift and my code is basically identical.

like image 287
T. Spikes Avatar asked Dec 12 '25 07:12

T. Spikes


2 Answers

@weissja19 was correct, I needed to set content type to application/json. Adding

urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")

fixed the error. Now the code works as I expected.

P.S. I couldn't catch it because I use the app Paw for testing, which sets content type automatically.

like image 152
T. Spikes Avatar answered Dec 14 '25 04:12

T. Spikes


You might want to do it manually:

urlRequest.httpBody = "name=\(languageName)".data(using: .utf8)

Use JSONSerialization will make your POST body like {"name":"abc"} which might not be supported by your server

like image 45
Tj3n Avatar answered Dec 14 '25 03:12

Tj3n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!