---
title: "#254: Dynamically Mocking Network Requests with Kakapo 🐤📡"
url: https://littlebitesofcocoa.com/254-dynamically-mocking-network-requests-with-kakapo
author: Jake Marsh
published: 2016-08-10
topics: ["Libraries","Networking","Testing"]
description: "Testing network requests can be tricky. Generating mock data, handling HTTP routes, etc. Thing get complicated quickly."
---

# #254: Dynamically Mocking Network Requests with Kakapo 🐤📡

By Jake Marsh, August 10, 2016. HTML: https://littlebitesofcocoa.com/254-dynamically-mocking-network-requests-with-kakapo

Testing network requests can be tricky. Generating mock data, handling HTTP routes, etc. Thing get complicated quickly. Today we'll check out a library from [devlucky](https://github.com/devlucky) called [Kakapo](https://github.com/devlucky/Kakapo) that can help us tame all this. Let's get started.

One of the best features of Kakapo is how easy it is start using. We can create a new **Router** for a domain, and start adding intercepted **routes** like this:

``` swift
let router = Router.register("http://littlebitesofcocoa.com")

router.get("/bites") { request in
  return ["id" : 1, "title": "#1: View Controller Initialization 🚀"]
}
```

In the above example, we're returning static data. Let's kick things up a notch and return some dynamic data. This is another place [Kakapo](https://github.com/devlucky/Kakapo) really shines:

``` swift
let db = KakapoDB()
db.create(Bite.self, number: 10)

router.get("/bites") { request in
  return db.findAll(Bite.self)
}
```

We can use this functionality to not only test **network requests**, but even to "stub out" **responses** before fully implementing backend services. Neat!

Once we've wired up some **routes**, we can make our **network requests** like normal:

``` swift
let URL = NSURL(string: "http://littlebitesofcocoa.com/1")!

session.dataTaskWithURL(URL) { (data, _, _) in
  // handle response
}.resume()
```

We can even wire Kakapo up to [Alamofire](https://github.com/Alamofire/Alamofire) ([Bite #93](https://littlebitesofcocoa.com/93-creating-a-router-for-alamofire)) like this:

``` swift
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses = [KakapoServer.self]
let manager = Manager(configuration: configuration)
```

This barely scratches the surface of what [Kakapo](https://github.com/devlucky/Kakapo) has to offer.

From [advanced dynamic mocking and database](https://github.com/devlucky/Kakapo#leverage-the-database---dynamic-mocking) functionality, [great routing](https://github.com/devlucky/Kakapo#router---register-and-intercept), and a [squeaky clean API](https://github.com/devlucky/Kakapo#customize-responses-with-responsefieldsprovider), it's definitely worth a look.

Learn more about [Kakapo](https://github.com/devlucky/Kakapo) at [git.io/kakapo](https://git.io/kakapo)
