Adding support for a REST API can give to your application a great appeal, since it shall be able to connect to remote web services (through the rest API) that can enhance the features of the application itself.

In this simple tutorial we are going to prepare a simple REST API using Slim Framework, and then we are going to make requests to the API using AlamoFire in swift.
The REST API will offer two requests:

  1. get the value of an item (GET)
  2. store a new value for an item using simple Authorization header (POST)

NOTE: this tutorial is not a step by step tutorial, you should be familiar with the following items:

  1. LAMP/WAMP/XAMP
  2. Swift
  3. PHP

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
Alamofire is an HTTP networking library written in Swift.

rest
Creating the REST API
The following lines have been run on UNIX systems, but they should work on Windows, too.

First of all we have to install the web server and the PHP language, you can find a package for your system that will install all that you need. Take a look at LAMP, WAMP, XAMP.
Open a terminal window and move to the httpdocs directory
$ cd /path/to/httpdocs

(on Linux you should move into /var/www)

Then we have to install composer (http://getcomposer.org).

$ curl -sS https://getcomposer.org/installer | php

Then create the Slim skeleton using composer:

$ php composer.phar create-project slim/slim-skeleton restapi

Edit the index.php inside the directory restapi/public/

$ vim restapi/public/index.php

Before the line containing “$app->run();” insert the following code:

$app->get('/item/:id', function($id) use ($app)
{
        $res["id"]           = $id;
        $res["associated"]   = $id + 100;
        echo json_encode($res);
});

$app->post('/item/', function() use ($app)
{
    $headers = getallheaders();
    $postdata = $app->request->getBody();
    $res = json_decode($postdata, true);
    if($headers['Authorization'] == "5ec49865cec46c66653a717e8801acdc")
    {
            $res["Error"] = false;
    }
    else
    {
            $res["Error"] = true;
    }
    echo json_encode($res);

});

The first function implements a GET request on the route http://127.0.0.1/restapi/public/item/, the request accepts a parameter in plain form and returns the parameter and a new value (parameter +100) in json format.

The second function implements a POST request on the route http://127.0.0.1/restapi/public/item/, the request accepts a parameter in json format and the Authorization code through the HTTP headers and returns back the input parameter with an error field set to false if the Authorization code is correct and true if it is not correct.

Download Alamofire

Open your favourite browser and goto https://github.com/Alamofire/Alamofire, click on the “Download Zip” button and wait for the completion of the download. Extract the zipped archive where you prefer.

Creating the swift project.
Open XCode and create a new Mac OS X Cocoa project, the language must be “swift”.
To install the downloaded AlamoFire into your project, follow the instructions at https://github.com/Alamofire/Alamofire for manual installation.

Modify the viewDidLoad method as follows:

override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let id = 12
        let req = "http://127.0.0.1/restapi/public/item/" + String(id)
        
        Alamofire.request(.GET, req)
        
            .responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                
                if let res = response.result.value {
                    print("res: \(res)")
                }
        }
        
        
        let parameters = ["value1": 12,
            "value2" : "string"
        ]
        
        
        let headers = [
            "content-type": "application/json; boundary=---011000010111000001101001",
            "Authorization": "5ec49865cec46c66653a717e8801acdc",
            "cache-control": "no-cache",
            "postman-token": "2b430c4d-62fd-ba18-a18b-9eecfdd994f6"
        ]

        
        Alamofire.request(.POST,"http://127.0.0.1/restapi/public/item/", parameters: parameters, encoding:ParameterEncoding.JSON	, headers: headers)
            .responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
        }
    }

Now run your application. In the output you should see something like the following lines

Optional(<NSMutableURLRequest: 0x608000003380> { URL: http://127.0.0.1/restapi/public/item/ })
Optional(<NSHTTPURLResponse: 0x600000030540> { URL: http://127.0.0.1/restapi/public/item/ } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 87;
    "Content-Type" = "text/html";
    Date = "Fri, 22 Jan 2016 07:13:01 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = "Apache/2.2.22 (Debian)";
    Vary = "Accept-Encoding";
    "X-Powered-By" = "PHP/5.4.45-0+deb7u2";
} })
Optional(<7b22416e 73776572 223a2253 74616d69 6e6b6961 20333322 2c225175 65737469 6f6e223a 22436869 20766f72 72657374 69206573 73657265 3f222c22 4572726f 72223a66 616c7365 7d>)
SUCCESS
JSON: {
    Answer = "Staminkia 33";
    Error = 0;
    Question = "Chi vorresti essere?";
}
Optional(<NSMutableURLRequest: 0x600000001000> { URL: http://127.0.0.1/restapi/public/item/12 })
Optional(<NSHTTPURLResponse: 0x60800002c620> { URL: http://127.0.0.1/restapi/public/item/12 } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 47;
    "Content-Type" = "text/html";
    Date = "Fri, 22 Jan 2016 07:13:01 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = "Apache/2.2.22 (Debian)";
    Vary = "Accept-Encoding";
    "X-Powered-By" = "PHP/5.4.45-0+deb7u2";
} })
Optional(<7b226964 223a2231 32222c22 6173736f 63696174 6564223a 3131327d>)
SUCCESS
res: {
    associated = 112;
    id = 12;
}

Some explanations about the swift code could be useful…..
To make a request with Alamofire you have to call the request method. Alamofire handles all the methods defined in RFC 7231 §4.3:
OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT

The first bunch of code makes a GET request.
Alamofire asynchronously waits for the response (see .responseJSON), as soon as the response will arrive it will be managed by the .responseJSON handler.

        let id = 12
        let req = "http://127.0.0.1/restapi/public/item/" + String(id)
        
        Alamofire.request(.GET, req)
        
            .responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization
                
                if let res = response.result.value {
                    print("res: \(res)")
                }
        }

The second request is more complex, since it sends the post parameters as HTTP body in json format and it also sends the HTTP headers containing the authorisation code.

     let parameters = ["value1": 12,
            "value2" : "string"
        ]
        
        
        let headers = [
            "content-type": "application/json; boundary=---011000010111000001101001",
            "Authorization": "5ec49865cec46c66653a717e8801acdc",
            "cache-control": "no-cache",
            "postman-token": "2b430c4d-62fd-ba18-a18b-9eecfdd994f6"
        ]

To sends parameters and headers you have to prepare the two dictionaries defined above, then you have to pass them to the Alamofire.request method

        Alamofire.request(.POST,"http://127.0.0.1/restapi/public/item/", parameters: parameters, encoding:ParameterEncoding.JSON	, headers: headers)

the .responseJSON handler is the same of the first request.

In this short tutorial we printed out the response, if you want to manage the response in son format SwiftyJSON can help you….
But this is another story.