Reputation: 763
How can I set the httpBody
for a URLRequest
to null
? (like the image below taken from Postman).
I have verified that the call ONLY works in Postman if the body is actually set to null
(raw JSON) as seen in the above. If the body is empty, or set to none, it fails (with a 415 error code if that matters to you).
My code:
guard let url = URL(string: "https://my-url.com/other/stuff") else { return nil }
var deleteRequest = URLRequest(url: url)
deleteRequest.httpMethod = "DELETE"
// I have tried all of these and they do not work
deleteRequest.httpBody = nil
deleteRequest.httpBody = Data()
deleteRequest.httpBody = ""
deleteRequest.httpBody = "null".data(using: .utf8)
deleteRequest.httpBody = try! JSONSerialization.data(withJSONObject: "", options: .fragmentsAllowed)
deleteRequest.httpBody = try! JSONSerialization.data(withJSONObject: NSNull(), options: .fragmentsAllowed)
PS: Unfortunately I can't share any more specific details about the request due to privacy reasons.
Upvotes: 0
Views: 73
Reputation: 763
Solved!
Turns out I needed to set the content-type to "application/json" like so: deleteRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
Setting the .httpBody
to anything is completely unneeded then.
Upvotes: 0