Write a Networking Layer in Swift 4 using Alamofire 5 and Codable Part 1: API Router

Nowadays consuming a web service API is an essential part of the modern mobile application development. In this article I want to share a simple way to setup a networking layer using Alamofire and Swift 4.

We will go through these steps while building the API client:

  1. API Router: the endpoint builder
  2. API Client: create and perform requests
  3. Codable: parsing JSON and mapping to data structure
  4. Use Future/Promises
  5. Use Reactive Programming (ReactiveCocoa and RxSwift)

In this first part we will focus on the request builder component.

API Router: the endpoint builder

It is important to have an API request builder component which presents an endpoint. The router will present an endpoint using HTTP method, HTTP headers, path and parameters

One of the recommended approaches is to create our API router using Swift Enum. Here is an implementation of the Router:

Endpoint builder

Ideally you have a Constants.swift file where you keep all your constants in one place


Instead if having just one router, if we have a several endpoints then we can split the routing logic into different routers, we can create a protocol to define a router:

Then we can implement it in each router for example we can have UserEndpoint :

Now we have clean representation of our API endpoints we are ready to make network requests and convert the JSON response to swift data models (classes and structs). That’s will be covered in the next part, in the meanwhile I would like to get your feedback about the Router implementation, for sure there is room for improvement.

Please feel free to comment and suggest any possible improvement, and please note that I’m not able to reply to any questions/comments here on Medium. Instead, please open a new issue in the example project GitHub repository:

You can read the next part here:

Thank you for reading.


You can find me on Linkedin and Twitter