MasterOnce
HomeBlogHow-To
3 min readFeb 25, 2026
Swift

How to Make a POST Request with URLSession

Send JSON data in a POST request.

Steps

  1. Paste the code into a Swift file or playground.
  2. Run it once to verify the output.
  3. 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.