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:
- API Router: the endpoint builder
- API Client: create and perform requests
- Codable: parsing JSON and mapping to data structure
- Use Future/Promises
- 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
One of the recommended approaches is to create our API router using Swift
Enum. Here is an implementation of the Router:
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
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:
NetworkingExample - Write a Networking Layer in Swift 4 using Alamofire 5 and Codablegithub.com
You can read the next part here:
In the previous part we have created the API Router for our networking layer which is in fact an enum that presents an…medium.com
Thank you for reading.