MasterOnce
HomeBlogHow-To
3 min readFeb 24, 2026
Swift

How to Make a GET Request with URLSession

Fetch data from a URL in a few lines.

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/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.