Write a Networking Layer in Swift 4 using Alamofire 5 and Codable Part 2: Perform request and parse using Codable

Alaeddine Messaoudi
6 min readDec 17, 2017

--

In the previous part we have created the API Router for our networking layer which is in fact an enum that presents an endpoint. In this part we will see how we will perform the request and parse the JSON response using Swift 4 Codable protocol.

Codable

Let’s start by defining our data models and conform to Codable protocol.

Here is our User model:

The simplest way to make a type codable is to declare its properties using types that are already Codable. These types include standard library types like String, Int, and Double; and Foundation types like Date, Data, and URL. Any type whose properties are codable automatically conforms to Codable just by declaring that conformance.

source: Encoding and Decoding Custom Types

It’s so easy to conform to Codable in case that your properties type are all part of the standard library types, like in our case we are just using String and URL

Our second Model will be Article :

Note here that some properties are optional like body, publisher and url , this is because we will not get these values when we will request the list of the articles. We will get this information only when we will fetch a specific article.

Here is the JSON response of the server when we fetch the list of articles:

And here is the response when we fetch a specific article:

Also note that in our Article model we are using a custom object Category so it’s not enough to just declare Article as Codable because we need to make sure that all properties of Article conforms to Codable, in this case the standard library types already conforms to Codable but our custom type Category should conform to Codable as well. Here is the implementation of Category model:

Now since Category is Codable our model Article is Codable as well. But here we have something new an enum called CodingKeys. It’s because the server will return a different key for the property parentID so then we need to specify the equivalent key returned by the server which is parent_id in our case.

Now all our models are Codable and are ready to be parsed. Let’s see now how we will perform the requests. For more information about Codable I recommend apple article Encoding and Decoding Custom Types

Requests

We need first to integrate Alamofire in our project. The recommended way is to use Carthage:

Note that we will be using Alamofire 5 which supports Decodable response serialization. Your Cartfile should be like:

github "Alamofire/Alamofire" "5.0.0-beta.3"

After integrating Alamofire we will create an APIClient class where we define our API requests. Let’s add first the login request:

You can see that we have now with Alamofire 5 a new method responseDecodable that will help us to make a request and returns a Decodable object/structure, in our case a User model. Note also here that we are using our APIRouter previously created in Part 1, since it’s an enum we need just to pass the parameters email and password and we are good to go.

Let’s try to test the login request:

We are just calling the static method in our APIClient and passing the correct parameters. After the execution our fetched and parsed user in printed in the console:

Let’s add another request to the APIClient. Let’s add the request to fetch the list of the articles. Our APIClient will be like this:

It’s almost the same as the login request but there is difference. We have passed a custom decoder. Let’s see first the documentation of the method responseDecodable:

We see here that there is two parameters queue and decoder with default parameters, that’s why in our first request of the login we have just passed one parameter when calling responseDecodable which is the completionHandler. In our request getArticles we need to use a custom JSONDecoder when calling responseDecodable because we need to parse a date with custom format. Here is a reminder of the JSON response of the articles endpoint :

So to help the JSONDecoder to know how to parse the date we need to specify a dateDecodingStrategy. We need to create first a DateFormatter :

Now after we have the the custom DateFormatter we create a new instance of JSONDecoder and then give it a dateDecodingStrategy value using our DateFormatter like this:

let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .formatted(.articleDateFormatter)

and finally we use our custom decoder when calling the method responseDecodable instead of the default one.

And when we test it:

We will get the array of the articles:

Now we have a fully functional networking layer that works with Alamofire 5 and Codable. But let’s refactor our APIClient and avoid the repetitive code :

We have just created a new method called performRequest that will perform the request when passing the APIRouter and the completion parameters. Also we made it possible pass a custom decoder.

Now we are happy with our APIClient and we have a complete networking layer which is ready to be used. Here is the full example project:

In the next part of this series we will try to improve our APIClient and use the concept of Future (sometimes also refereed as Promise) instead of the completion callback that we are using now. It will help as to better handle the response.

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:

Stay tuned and don’t forget to follow to be notified once the next parts are published.

You can read the next part here:

Thank you for reading.

You can find me on Linkedin and Twitter

--

--