[NOTE: This has been edited for clarity since there seems to be some confusion about what I want. I only want the raw JSON. In this case, it should be {"foo":"bar"}
. It is important to highlight that I want this as a string! I don't need it decoded into a Swift object or marshaled or modified in any way!]
Is it possible to get the raw JSON from an API call? Currently I'm using URLSession.dataTask(with:request)
but the response data includes the response header along with the body. I only want the raw JSON as it comes back to me, as a string.
Here is the code I'm using:
// Build the URL
var urlComponents = URLComponents()
urlComponents.scheme = "http"
urlComponents.host = "127.0.0.1"
urlComponents.port = 80
urlComponents.queryItems = [URLQueryItem(name: "foo", value: "bar")]
guard let url = urlComponents.url else {
fatalError("Could not create URL from components")
}
// Configure the request
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) {(responseData, response, error) in
DispatchQueue.main.async {
guard error == nil else {
print("ERROR: \(String(describing: error))")
return
}
guard let _ = response else {
print("Data was not retrieved from request")
return
}
print("JSON String: \(String(describing: String(data: responseData!, encoding: .utf8)))")
if let resData = responseData {
let jsonResponse = try? JSONSerialization.jsonObject(with: resData, options: [])
if let response = jsonResponse as? [String: Any] {
print("RESPONSE:")
dump(response)
} else {
print("SOMETHING WENT WRONG")
}
}
}
}
task.resume()
This produces the following in the console:
JSON String: Optional("HTTP/1.1 OK\nContent-Type: application/json\n\n{\"foo\":\"bar\"}")
SOMETHING WENT WRONG