3 min readFeb 24, 2026
SwiftHow to Make a GET Request with URLSession
Fetch data from a URL in a few lines.
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/status")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error:", error)
return
}
guard let data = data else { return }
print("Bytes:", data.count)
}
task.resume()Notes
- Keep functions small and focused for reuse.
- Prefer safe APIs like optionals and guards.
