Search code examples
swifthttp-headersaccess-token

Add API Key in X-Auth-Token in Swift?


I'm using this website football-data.org API to get JSON data.

But, there's a limit of 50 req/day unless you get the API key and integrate it. I'm cool with doing that, the problem is I have no idea how.

I have already register and got my API Key and in the email also says:

Please modify your client to use a header-field named "X-Auth-Token" with the underneath personal token as value.

Your API token: 4180b1645f624408b6291349204122344

He gave an example code in other programming languages, such as in PHP:

<?php
$uri = 'http://api.football-data.org/alpha/soccerseasons/354/fixtures/?matchday=22';
$reqPrefs['http']['method'] = 'GET';
$reqPrefs['http']['header'] = 'X-Auth-Token: YOUR_TOKEN';
$stream_context = stream_context_create($reqPrefs);
$response = file_get_contents($uri, false, $stream_context);
$fixtures = json_decode($response);
?>

But that means nothing to me.

How do we do that in Swift? I tried to Google it but couldn't find anything.


Solution

  • Assuming you're using a native iOS API for making HTTP requests:

    let request = NSMutableURLRequest(URL: NSURL(string: "http://endpoint")!)
    request.addValue("4180b1645f624408b6291349204122344", forHTTPHeaderField: "X-Auth-Token")
    request.HTTPMethod = "GET" // or POST or whatever
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
        // handle your data here
    }