---
title: "#150: Standardizing Network Abstractions with Moya 🌐👔"
url: https://littlebitesofcocoa.com/150-standardizing-network-abstractions-with-moya
author: Jake Marsh
published: 2015-12-18
topics: ["Libraries","Networking"]
description: "Way back in Bite #93 we talked about creating a \"router\" for Alamofire that would generate URL requests from enum cases."
---

# #150: Standardizing Network Abstractions with Moya 🌐👔

By Jake Marsh, December 18, 2015. HTML: https://littlebitesofcocoa.com/150-standardizing-network-abstractions-with-moya

Way back in [Bite #93](https://littlebitesofcocoa.com/93) we talked about creating a "router" for **Alamofire** that would generate **URL requests** from **enum cases**.

In most apps we'll likely end up with some version of that code to help communicate with the API for that particular app. It'd be great if there was some sort of "standard" way to write this code each time.

Today we'll look at a library called [Moya](https://github.com/Moya/Moya) that aims to provide this. Let's dive in. 🏊

[Moya](https://github.com/Moya/Moya) is a network abstraction layer that encapsulates calling [Alamofire](https://github.com/Alamofire/Alamofire) functions. It helps us avoid creating messy custom network abstractions in every project.

<img src="https://media.littlebitesofcocoa.com/bite-assets/150-standardizing-network-abstractions-with-moya-graphic.png" style="max-width: 438px;" />

To use [Moya](https://github.com/Moya/Moya) in an app, we'll need an **enum** with a **case** representing each API endpoint we want to hit:

``` swift
enum FirstOrder { case AllTroops; case Troop(String) }
```

Then we'll extend it to conform to _Moya's_ `TargetType` **protocol**:

``` swift
extension FirstOrder: TargetType {
  var baseURL: NSURL {
    return NSURL(string: "https://api.firstorder.galaxy.far.away")!
  }

  var path: String {
    switch self {
    case .AllTroops: return "/troops"
    case .Troop(let id): return "/troops/\(id)"
    }
  }

  var method: Moya.Method { return .GET }

  var parameters: [String: AnyObject]? {
    switch self {
    case .AllTroops: return ["sort": "recent"]
    default: return nil
    }
  }

  var sampleData: NSData {
    switch self {
    case .AllTroops:
      return "[{\"id\": \"FN-2187\"}]".dataUsingEncoding(NSUTF8StringEncoding)!
    case .Troop(let id):
      return "{\"id\": \"\(id)\"}".dataUsingEncoding(NSUTF8StringEncoding)!
    }
  }
}
```

Finally, we'll create a new _Moya provider_ using our **enum** and make it available globally:

``` swift
let FirstOrderAPI = MoyaProvider<FirstOrder>()
```

Now we can make requests like this:

``` swift
FirstOrderAPI.request(.Troop("FN-2187")) { result in
  switch result {
  case .Success(let response):
    do {
      let json = try response.mapJSON()
      // TODO: Parse JSON
    } catch(let error) { handleError(error) }
  case .Failure(let error): handleError(error)
  }
}
```

This is just a taste, [Moya](https://github.com/Moya/Moya) has a ton to offer including some fantastic enforcement of good testing practices.

In conforming to the `TargetType` **protocol**, we're actually required to provde `sampleData`. We can also customize things further by providing an `endpointClosure` when creating our **provider**.

More info about _Moya_ can be found at [git.io/moya](http://git.io/moya)
