3 min readFeb 25, 2026
SwiftHow to Make a POST Request with URLSession
Send JSON data in a POST request.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- Adjust the inputs to match your use case.
Copy and paste
import Foundation
let url = URL(string: "https://api.example.com/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let payload = ["email": "[email protected]", "password": "secret"]
request.httpBody = try JSONSerialization.data(withJSONObject: payload)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error:", error)
return
}
print("Success")
}
task.resume()Notes
- Keep functions small and focused for reuse.
- Prefer safe APIs like optionals and guards.
