In this Swift tutorial, you will learn how to send HTTP GET Request in Swift. You will also learn how to set request parameters and HTTP request headers and how to read HTTP Response. To summarize, this tutorial will cover:
- Send HTTP Get Request,
- Set HTTP Request Headers,
- Read HTTP Response Status Code,
- Read HTTP Response Headers,
- Read HTTP Response Body,
- Convert JSON HTTP Response to a Swift struct.
Public RESTful Web Service Endpoint
In this tutorial, I will use public and free at the time of writing this tutorial RESTful Web Service: https://jsonplaceholder.typicode.com. This web service endpoint allows me to send HTTP Requests to it and get back JSON response. For example, if I open the following URL in the browser windows: https://jsonplaceholder.typicode.com/todos/1 I will get back the following JSON document:
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
Sending HTTP GET Request
Below is a very simple example of how you can send an HTTP GET Request in Swift. Please note the comments in the code.
// Create URL let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") guard let requestUrl = url else { fatalError() } // Create URL Request var request = URLRequest(url: requestUrl) // Specify HTTP Method to use request.httpMethod = "GET" // Send HTTP Request let task = URLSession.shared.dataTask(with: request) { (data, response, error) in // Check if Error took place if let error = error { print("Error took place \(error)") return } // Read HTTP Response Status code if let response = response as? HTTPURLResponse { print("Response HTTP Status code: \(response.statusCode)") } // Convert HTTP Response Data to a simple String if let data = data, let dataString = String(data: data, encoding: .utf8) { print("Response data string:\n \(dataString)") } } task.resume()
Set HTTP Request Header
If your HTTP Request needs to contain specific HTTP Request Headers, then below is an example of how you can do it.
var request = URLRequest(url: requestUrl) request.httpMethod = "GET" // Set HTTP Request Header request.setValue("application/json", forHTTPHeaderField: "Accept")
You can set more than one header.
request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("Basic htu574kfj584kfnd84kdlwut92jayebgpylg8md72msgrk", forHTTPHeaderField: "Authorization")
Read HTTP Response Header
Once you have received HTTP Response, you can then read from that HTTPURLResponse object all HTTP Request headers at once or if you know the HTTP request header name, then you can read the value of that specific header.
Read All Header Fields
let allHeaderFields:[AnyHashable : Any] = response.allHeaderFields print("All headers: \(allHeaderFields)")
Read a Specific Header
let contentTypeHeader = response.value(forHTTPHeaderField: "Content-Type")
and here how it is being used when HTTP Response is received:
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let response = response as? HTTPURLResponse { // Read all HTTP Response Headers print("All headers: \(response.allHeaderFields)") // Read a specific HTTP Response Header by name print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")") } } task.resume()
Read HTTP Response Body
When HTTP Response arrives, you will most likely need to read its HTTP Response Body. Use the below code snippet to convert the HTTP Response Body/Data to a human-readable String value.
if let data = data, let dataString = String(data: data, encoding: .utf8) { print("Response data string:\n \(dataString)") }
and here how it looks if used with URLSession data task:
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let data = data, let dataString = String(data: data, encoding: .utf8) { print("Response data string:\n \(dataString)") } } task.resume()
Convert Data to Dictionary
If the above HTTP Get request is called, the response body will contain a JSON string which can be easily converted to a Dictionary. Here is how the returned JSON string looks:
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
Now lets convert it to a Swift Dictionary:
do { if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary { // Print out entire dictionary print(convertedJsonIntoDict) // Get value by key let userId = convertedJsonIntoDict["userId"] print(userId ?? "userId could not be read") } } catch let error as NSError { print(error.localizedDescription) }
Covert Data to Swift Structure
We can also convert Data object into a Swift structure. To do that we need to create a Swift struct that contains field names which match the JSON string. Here is how the JSON string read from the response body looks. When read from HTTP Response the below JSON string is in a form of Data:
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
Here is how our Swift struc must look:
struct ToDoResponseModel: Codable { let userId: Int let id: Int let title: String let completed: Bool }
Here is how to convert Data into Swift struct:
func parseJSON(data: Data) -> UserResponseModel? { var returnValue: UserResponseModel? do { returnValue = try JSONDecoder().decode(UserResponseModel.self, from: data) } catch { print("Error took place\(error.localizedDescription).") } return returnValue }
Lets put this together:
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data else { return } // Using parseJSON() function to convert data to Swift struct let todoItem = parseJSON(data: data) // Read todo item title guard let todoItemModel = todoItem else { return } print("Todo item title = \(todoItemModel.title)") } task.resume()
I hope this tutorial was helpful to you. Check other Swift tutorials on this web site and you will find a lot of useful code examples to use.