I need to fetch data from a web endpoint. I will include the instructions below. I am passing the the X-ACCESS-KEY incorrectly because I get the error that the key is invalid or the bin doesn't belong to my account when I run the code. How do I correctly pass the key to the request then decode the response?
we've hosted a JSON file at at this url: https://api.jsonbin.io/v3/b/646bed328e4aa6225ea22a79. Your job is to write a script to download the contents of the URL (hint: The X-ACCESS-KEY is $2b$10$Ke1iwieFO7/7qsSKU.GYU.oYXZMW1EeHrwd4xx9ylboJik5mstZk6) sort the data by each elements 'bar' key filter out elements where 'baz' is not divisible by 3 concatenate each elements 'foo' value
let url = URL(string: "https://api.jsonbin.io/v3/b/646bed328e4aa6225ea22a79")!
let key = "$2b$10$Ke1iwieFO7/7qsSKU.GYU.oYXZMW1EeHrwd4xx9ylboJik5mstZk6)"
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(key)", forHTTPHeaderField: "X-Master-Key")
var jsonData: Data?
let task = URLSession.shared.dataTask(with: request) { (data, _, err) in
if let error = err {
print("Error: \(error)")
} else if let data = data {
jsonData = data
processData()
}
}
task.resume()
func processData(){
if let jsonData = jsonData,
let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any], let records = jsonObject["records"] as? [[String: Any]] {
}
}
Three issues:
Joakim correctly stated that you have to specify just the key without leading Bearer
.
And the hint clearly says it's X-Access-Key
not X-Master-Key
request.addValue(key, forHTTPHeaderField: "X-Access-Key")
The closing parenthesis at the end is not part of the token.