<commit_before># Swallow

[![Build Status](https://travis-ci.org/TheHolyGrail/Swallow.svg)](https://travis-ci.org/TheHolyGrail/Swallow)

Swallow simplifies interaction with HTTP web services by providing a concise API for encoding `NSURLRequest` objects and processing the resulting `NSURLResponse` object. Designed as a lightweight utility for communicating with web services, Swallow is not intended to be a fully-featured networking library. By default Swallow uses the shared `NSURLSession` instance to create data tasks but can be configured to work with any NSURLSession instance using a [protocol](#sessiondatataskdatasource).

## Usage

At the highest level a request for a resource could look like the following:

```
// fetch list of stores based on zip code value
WebService(baseURLString: "https://somehapi.herokuapp.com")
    .fetchStores(zipCode: "15217")
    .responseStores { (stores: [StoreModel]?) in
      // update UI with model data
    }
    .responseError { response, error in
      // I am error
    }
```

The `WebService` structure and `ServiceTask` class provide the basic building blocks to make this short and simple syntax possible.

### Sending HTTP Requests

At the lowest level `WebService` supports an API for making a HTTP request and processing the raw response data.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response { (response: NSURLResponse?, data: NSData?) in
    // process response data
  }
```

Add a `responseError()` handler to handle the possibility of a failed request.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response { (response: NSURLResponse?, data: NSData?) in
    // process response data
  }
  .responseError { (error: NSError?) in
    // I am error
  }
```

The `responseError()` handler will only be called when a request results in an error. If an error occurs all other response handlers will not be called. This pattern allows you to cleanly separate the logic for handling success and failure cases.

### Response Handlers

Response handlers can be chained to process the response of the request. After the response is received handlers are invoked in the order of which they are declared.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response { (response: NSURLResponse?, data: NSData?) in
    // process raw response
  }
  .responseJSON { json in
    // process response as JSON
  }
```

### Extensions

The chainable response handler API makes it easy to create custom response handlers using extensions.

```
// MARK: - Store Locator Services

extension ServiceTask {
    
    public typealias StoreServiceSuccess = ([StoreModel]?) -> Void
    
    func responseStores(handler: StoreServiceSuccess) -> Self {
        
        return responseJSON { json in
            if let models: [StoreModel]? = self.parseJSONAsStoreModels(json) {
                handler(models)
            }
        }
    }
}
```

This allows you to wrap the details of how the response is processed in a high-level convenience method enabling you to simplify how consumers interact with your web service API.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .responseStores { (stores: [StoreModel]?) in
    // process resonse as model objects and update UI
  }
  .responseError { error in
    // I am error
  }
```

Extensions are also useful for wrapping the details of the web service requests. This is an ideal approach because all of the details of the HTTP request are declared inline with the service call method.

```
public extension WebService {
    
    public func fetchStores(zipCode aZipCode: String) -> ServiceTask {
        
        return GET("/stores", parameters: ["zip" : aZipCode])
    }
}
```

Extensions are powerful constructs for wrapping the HTTP details of a web service call and provide a mechanism for your code to be declaritive about how to interact with web services.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
    .fetchStores(zipCode: "15217")
    .responseStoreModels { models in
      // update UI
    }
    .responseError { response, error in
      // I am error
    }
```

### Request Parameters

Request parameters are percent encoded and appended as a query string of the request URL for `GET` and `HEAD` requests. For all other request methods, parameters are sent as the request body and are encoded based on the `parameterEncoding` endpoint option.

##### Parameter Encodings

- `.Percent` - Encode parameters as a percent encoded query string.
- `.JSON` - Encode parameters as a JSON object.

##### Sending Parameters

Send a `GET` request with query parameters.

```
let parameters = ["foo" : "bar", "percentEncoded" : "this needs percent encoded"]
        
WebService(baseURLString: "http://httpbin.org")
    .GET("/get", parameters: parameters)
```

HTTP


```
GET /stores?percentEncoded=this%20needs%20percent%20encoded&foo=bar HTTP/1.1

```


Send a `POST` request with body parameters.

```
let parameters = ["foo" : "bar", "percentEncoded" : "this needs percent encoded"]
        
WebService(baseURLString: "http://httpbin.org")
    .POST("/post", parameters: parameters)
```

HTTP

```
POST /stores HTTP/1.1
Content-Length: 55

percentEncoded=this%20needs%20percent%20encoded&foo=bar
```

Send a `POST` request with JSON encoded parameters.

```
let parameters = ["foo" : "bar", "number" : 42]
var options = WebService.EndpointOptions()
options.parameterEncoding = .JSON

WebService(baseURLString: "http://httpbin.org")
    .POST("/post", parameters: parameters, options: options)
```

HTTP

```
POST /post HTTP/1.1
Content-Type: application/json
Content-Length: 25

{"number":42,"foo":"bar"}
```

### Protocols

##### SessionDataTaskDataSource

The `SessionDataTaskDataSource` protocol is provided to allow Swallow to work with any NSURLSession-based API. Types conforming to the `SessionDataTaskDataSource` protocol are responsible for creating `NSURLSessionDataTask` objects based on a `NSURLRequest` value and invoking a completion handler after the response of a data task has been received.

By default Swallow implements the `SessionDataTaskDataSource` protocol as a private structure using the shared session returned from `NSURLSession.sharedSession()`. 

### Dispatch Queues

The dispatch queue used to execute the response handler can be specified as the first parameter of a response handler. Unless specified all response handler are run on the main dispatch queue.

```
let queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)

WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response(queue) { (response: NSURLResponse?, data: NSData?) in
    // process response data
  }
```

### KillerRabbit<commit_msg>add usage info about request options<commit_after># Swallow

[![Build Status](https://travis-ci.org/TheHolyGrail/Swallow.svg)](https://travis-ci.org/TheHolyGrail/Swallow)

Swallow simplifies interaction with HTTP web services by providing a concise API for encoding `NSURLRequest` objects and processing the resulting `NSURLResponse` object. Designed as a lightweight utility for communicating with web services, Swallow is not intended to be a fully-featured networking library. By default Swallow uses the shared `NSURLSession` instance to create data tasks but can be configured to work with any NSURLSession instance using a [protocol](#sessiondatataskdatasource).

## Usage

At the highest level a request for a resource could look like the following:

```
// fetch list of stores based on zip code value
WebService(baseURLString: "https://somehapi.herokuapp.com")
    .fetchStores(zipCode: "15217")
    .responseStores { (stores: [StoreModel]?) in
      // update UI with model data
    }
    .responseError { response, error in
      // I am error
    }
```

The `WebService` structure and `ServiceTask` class provide the basic building blocks to make this short and simple syntax possible.

### Sending HTTP Requests

At the lowest level `WebService` supports an API for making a HTTP request and processing the raw response data.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response { (response: NSURLResponse?, data: NSData?) in
    // process response data
  }
```

Add a `responseError()` handler to handle the possibility of a failed request.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response { (response: NSURLResponse?, data: NSData?) in
    // process response data
  }
  .responseError { (error: NSError?) in
    // I am error
  }
```

The `responseError()` handler will only be called when a request results in an error. If an error occurs all other response handlers will not be called. This pattern allows you to cleanly separate the logic for handling success and failure cases.

### Response Handlers

Response handlers can be chained to process the response of the request. After the response is received handlers are invoked in the order of which they are declared.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response { (response: NSURLResponse?, data: NSData?) in
    // process raw response
  }
  .responseJSON { json in
    // process response as JSON
  }
```

### Extensions

The chainable response handler API makes it easy to create custom response handlers using extensions.

```
// MARK: - Store Locator Services

extension ServiceTask {
    
    public typealias StoreServiceSuccess = ([StoreModel]?) -> Void
    
    func responseStores(handler: StoreServiceSuccess) -> Self {
        
        return responseJSON { json in
            if let models: [StoreModel]? = self.parseJSONAsStoreModels(json) {
                handler(models)
            }
        }
    }
}
```

This allows you to wrap the details of how the response is processed in a high-level convenience method enabling you to simplify how consumers interact with your web service API.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .responseStores { (stores: [StoreModel]?) in
    // process resonse as model objects and update UI
  }
  .responseError { error in
    // I am error
  }
```

Extensions are also useful for wrapping the details of the web service requests. This is an ideal approach because all of the details of the HTTP request are declared inline with the service call method.

```
public extension WebService {
    
    public func fetchStores(zipCode aZipCode: String) -> ServiceTask {
        
        return GET("/stores", parameters: ["zip" : aZipCode])
    }
}
```

Extensions are powerful constructs for wrapping the HTTP details of a web service call and provide a mechanism for your code to be declaritive about how to interact with web services.

```
WebService(baseURLString: "https://somehapi.herokuapp.com")
    .fetchStores(zipCode: "15217")
    .responseStoreModels { models in
      // update UI
    }
    .responseError { response, error in
      // I am error
    }
```

### Request Parameters

Request parameters are percent encoded and appended as a query string of the request URL for `GET` and `HEAD` requests. For all other request methods, parameters are sent as the request body and are encoded based on the `parameterEncoding` endpoint option.

##### Parameter Encodings

- `.Percent` - Encode parameters as a percent encoded query string.
- `.JSON` - Encode parameters as a JSON object.

##### Sending Parameters

Send a `GET` request with query parameters.

```
let parameters = ["foo" : "bar", "percentEncoded" : "this needs percent encoded"]
        
WebService(baseURLString: "http://httpbin.org")
    .GET("/get", parameters: parameters)
```

HTTP


```
GET /stores?percentEncoded=this%20needs%20percent%20encoded&foo=bar HTTP/1.1

```


Send a `POST` request with body parameters.

```
let parameters = ["foo" : "bar", "percentEncoded" : "this needs percent encoded"]
        
WebService(baseURLString: "http://httpbin.org")
    .POST("/post", parameters: parameters)
```

HTTP

```
POST /stores HTTP/1.1
Content-Length: 55

percentEncoded=this%20needs%20percent%20encoded&foo=bar
```

Send a `POST` request with JSON encoded parameters.

```
WebService(baseURLString: "http://httpbin.org")
    .POST("/post", 
        parameters: ["foo" : "bar", "number" : 42], 
        options: [.ParameterEncoding(.JSON)])
```

HTTP

```
POST /post HTTP/1.1
Content-Type: application/json
Content-Length: 25

{"number":42,"foo":"bar"}
```

### Options

An array of Option enum values can be passed as additional information to encode in the request.

```
WebService(baseURLString: "http://httpbin.org")
    .POST("/post", 
        parameters: ["foo" : "bar", "number" : 42], 
        options: [.ParameterEncoding(.JSON),
                  .Header("custom-header", "12345"),
                  .Header(Request.Headers.userAgent, "my app ua")])
```

### Protocols

##### SessionDataTaskDataSource

The `SessionDataTaskDataSource` protocol is provided to allow Swallow to work with any NSURLSession-based API. Types conforming to the `SessionDataTaskDataSource` protocol are responsible for creating `NSURLSessionDataTask` objects based on a `NSURLRequest` value and invoking a completion handler after the response of a data task has been received.

By default Swallow implements the `SessionDataTaskDataSource` protocol as a private structure using the shared session returned from `NSURLSession.sharedSession()`. 

### Dispatch Queues

The dispatch queue used to execute the response handler can be specified as the first parameter of a response handler. Unless specified all response handler are run on the main dispatch queue.

```
let queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)

WebService(baseURLString: "https://somehapi.herokuapp.com")
  .GET("/stores", parameters: ["zip" : "15217"])
  .response(queue) { (response: NSURLResponse?, data: NSData?) in
    // process response data
  }
```

### KillerRabbit
{'fraction_non_alphanumeric': 0.10461388346807918, 'fraction_numerical': 0.00913019236130471, 'mean_word_length': 3.944521019986216, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 18, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7330756', 'n_tokens_mistral': 4108, 'n_tokens_neox': 3883, 'n_words': 1550}