tezvyn:

URLRequest: The Blueprint for a Network Call

AI-drafted, machine-checkedSource: developer.apple.combeginner
URLRequest: The Blueprint for a Network Call

URLRequest is the recipe for a network call, not the call itself. It bundles the URL, HTTP method, headers, and body. You hand this 'order form' to URLSession to execute. The footgun is thinking URLRequest sends the request—it only describes it.

WHY IT EXISTS: URLRequest exists to decouple the configuration of a network request from its execution. By creating a self-contained description of a request, you can pass it around, modify it, and test its properties without actually hitting the network. This separation makes code cleaner and more modular.

THE MENTAL MODEL: A URLRequest is like an order form for a restaurant. You fill out what you want (the URL), how you want it prepared (the HTTP method like GET or POST), and any special instructions (HTTP headers like an auth token). You haven't sent the order yet. You hand this completed form to a waiter (URLSession), who takes it to the kitchen to be fulfilled.

HOW IT WORKS: You initialize a URLRequest with a URL. Since it's a struct, you then set its properties to configure the request. You might set httpMethod to "POST", add an "Authorization" token to the allHTTPHeaderFields dictionary, and assign encoded JSON data to the httpBody property. Finally, you pass this complete URLRequest object to a URLSession data task to be executed.

WHEN TO USE IT: Use URLRequest for any network call that isn't a simple, default GET. This includes any time you need to specify a method (POST, PUT, DELETE), send data in a request body, or provide custom HTTP headers for things like content type or authentication. It makes your networking code explicit and easy to read.

WHEN NOT TO USE IT: For the absolute simplest GET request with no special headers, you can technically use the URLSession data task that accepts just a URL. However, even then, using a URLRequest is often clearer. Do not use URLRequest for accessing local files on the device; use the FileManager API for that purpose.

ONE CANONICAL EXAMPLE: To send a user's new profile name to a server, you would create a URLRequest for the '.../api/user/profile' endpoint. You'd set its httpMethod to "PUT". You would encode the new name into JSON data and assign it to the httpBody. You would also set two headers: "Content-Type" to "application/json" and "Authorization" to "Bearer <your_token>". This request is then ready to be sent by URLSession.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.