4

I am currently trying implement Tracker Networks API into an Xcode project. I know how to do this using Node.js and html, but can’t seem to figure it out using Swift in Xcode.

The website says to use a get request using this —> “GET https://api.fortnitetracker.com/v1/store

And then they say to, “To make use of our APIs we require you to use an API Key. To use the API key you need to pass it along as a header with your requests.”

And here is my API key (fake api key): TRN-Api-Key: d93742a5-94d0-482c-8714-23c6660225555

If some could show me how to set this up it’d mean a lot to me. Thanks.

  • 1
    Well, the message is pretty self explanatory, you need to send the API key inside the requests' **headers**. [This question](https://stackoverflow.com/questions/40247922/swift-alamofire-4-add-header-to-request-without-custom-request-adapter) asks for doing that, using the Alamofire library (which you should use too). The `headers` parameter should be created like this `let headers: HTTPHeaders = ["api_key_header_name" : "my_api_key"]`. How to name that header depends on the API, check out their documentation. – Alejandro Iván Oct 10 '18 at 01:52

2 Answers2

5

Here's a quick answer that will hopefully point you in the right direction.

  • Step 1: Download Postman
  • Step 2: Open up Postman, paste your url into the GET field
  • Step 3: Click the "Headers" tab.

TRN-Api-Key is going to be the key, your API key will be the value. It'll look like this.

enter image description here

Play around with Postman making calls, make sure they work, etc. It's a lot easier than ****ing around with Xcode setting breakpoints, etc. Once you've got it figured out what calls you're going to be making...then go to Xcode.

Once you've got your GETs kicking back JSONs, then cut and paste it into something like https://app.quicktype.io. For the endpoint in the example URL I'm using, it gives you this:

struct Response: Codable {
    let items: [Item]
}

struct Item: Codable {
    let metadata: [Metadatum]
}

struct Metadatum: Codable {
    let key: String
    let value: String?
}
  • Step 4: Look into URLComponents. That'll be how you create URLs to feed to your URLRequests.

  • Step 5: When you make URLRequests, you'll need to dump in the API key name and the API key value into the header. It should be pretty self-explanatory on the documentation page.

Here's the basic "physics for poets" code:

let fortniteChallengesURL = URL(string: "https://api.fortnitetracker.com/v1/challenges")
if let unwrappedURL = fortniteChallengesURL {
    var request = URLRequest(url: unwrappedURL)
    request.addValue("YOUR API KEY", forHTTPHeaderField: "TRN-Api-Key")
    // Make your request and handle the response
}

Alternatively (perhaps preferably), you can use a networking framework like Alamofire for making requests. Here's how to customize headers in Alamofire.

Here's how to use the Codable structs in parsing the returns from your endpoint.

Here's the finished product using Apple's "factory" classes, if you want to dump it into a playground. You'll need your own API key.

struct Response: Codable {
    let items: [Item]
}

struct Item: Codable {
    let metadata: [Metadatum]
}

struct Metadatum: Codable {
    let key: String
    let value: String?
}

let fortniteChallengesURL = URL(string: "https://api.fortnitetracker.com/v1/challenges")
if let unwrappedURL = fortniteChallengesURL {
    var request = URLRequest(url: unwrappedURL)
    request.addValue("YOUR API KEY HERE", forHTTPHeaderField: "TRN-Api-Key")
    let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
        // you should put in error handling code, too
        if let data = data {
            do {
                let json = try JSONDecoder().decode(Response.self, from: data) as Response
                // HERE'S WHERE YOUR DATA IS
                print(json.items.count)
            } catch {
                print(error.localizedDescription)
            }
        }
    }
    dataTask.resume()
}
Adrian
  • 16,233
  • 18
  • 112
  • 180
  • This really helped a lot both you and @Zaid. I have also added a way for the json to print out nicer and then commented it out. Thanks a lot. –  Oct 10 '18 at 06:35
  • I've been in your shoes where there's a snippet of an answer, but plenty of blanks. APIs are a lot of fun when you "get the hang of it". I think I might get my kid a key for this so he can tinker with that API. – Adrian Oct 10 '18 at 13:28
4

Use this sample code to add it to the header field:

if let url = URL(string: "https://api.fortnitetracker.com/v1/store") {
    let request = URLRequest(url: url)
    request.addValue("d93742a5-94d0-482c-8714-23c6660225555", forHTTPHeaderField: "TRN-Api-Key"
    request.httpMethod = "GET"
    let dataTask = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        //handle response here
    }
    dataTask.resume()
}
Zaid M. Said
  • 314
  • 1
  • 15
  • 2
    LOL! The OP sounded like he was starting at ground zero, so I threw more in than I needed to. Your answer definitely more succinct. – Adrian Oct 10 '18 at 03:34
  • The variable request should not be a constant, it should be revised to : var request = URLRequest(url: url) – Daniel Sogbey May 14 '23 at 17:22