Sending HTTP GET Request in Swift

In this tutorial, you will learn how to send HTTP GET requests using Swift.

HTTP GET requests are used to retrieve data from a server. They are one of the most common types of HTTP requests, and they are often used to access RESTful APIs.

When you send a GET request, you’re asking the server to send back data that corresponds to the specific URL you’ve requested.

To learn how to send HTTP POST requests in Swift, please read this tutorial: Sending HTTP Posts requests in Swift.

Step 1: Creating a URL and URLRequest

To make an HTTP GET request in Swift, you first need to create a URL object that represents the API endpoint you want to access.

Then, you create a URLRequest object using the URL. This request object will be used to specify the details of the HTTP request, such as the HTTP method (GET in this case).

// Create a URL
let url = URL(string: "https://www.swiftdeveloperblog.com/my-http-get-example-script/")
guard let requestUrl = url else { fatalError("Invalid URL") }

// Create a URLRequest
var request = URLRequest(url: requestUrl)
request.httpMethod = "GET" // Specify the HTTP method

Step 2: Sending the HTTP GET Request

To send the HTTP GET request, you use the URLSession class, which is a part of the Foundation framework.

Specifically, you use the dataTask(with:completionHandler:) method of URLSession.shared, passing in the URLRequest you created and a completion handler.

The completion handler is a closure that gets called when the request is complete, providing you with the data returned by the server, the response, and any error that occurred.

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print("Error: \(error)")
    } else if let data = data {
        // Process the data here
    }
}
task.resume()

Step 3: Add Authorization HTTP Request Header

Basic Authentication

If the API you’re accessing requires authentication, you might need to add an Authorization header to your request. This is typically done using the setValue(_:forHTTPHeaderField:) method of the URLRequest object.

request.setValue("Basic your_auth_token_here", forHTTPHeaderField: "Authorization")

Bearer JWT

Similar to basic authentication, if the API uses a bearer token for authentication, you can add it to the request header as follows:

request.setValue("Bearer your_auth_token_here", forHTTPHeaderField: "Authorization")

Step 5: Handling the HTTP Response

After sending the request, you’ll receive a response that includes the data returned by the server. You can process this data within the completion handler you provided to the dataTask(with:completionHandler:) method. If the data is in JSON format, you might need to parse it into a Swift object.

Sending HTTP GET Request: Complete code example

Here’s how all the steps come together in a complete example using SwiftUI:

import SwiftUI

struct ContentView: View {
    
    func performHTTPGetRequest() {
        let url = URL(string: "https://www.swiftdeveloperblog.com/my-http-get-example-script/")!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("Basic your_auth_token_here", forHTTPHeaderField: "Authorization")

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("Error: \(error)")
            } else if let data = data {
                print("Data received: \(String(data: data, encoding: .utf8) ?? "No data")")
            }
        }
        task.resume()
    }

    var body: some View {
        VStack {
            Button("Perform Request", action: {
                performHTTPGetRequest()
            })
        }
    }
}

Send HTTP GET Request example using Swift

Conclusion

I hope this tutorial was helpful to you.

To learn more about Swift and to find other code examples, check the following page: Swift Code Examples.

Happy learning!