Using Generics to handle GET and POST requests (Swift)

Nabin Shrestha
2 min readMay 3, 2020

Most of the mobile applications basically function by fetching data from the server and makes requests to the server based on the user action performed.

So, in our application we have a NetworkService or ApiService class that handles most of the network related works i.e. GET and POST requests.

For example, we have obtain following json data from the url:

https://gist.github.com/nabs107/c39c9206df72573d66576e5085398ed3

So, for that we firstly create a new class named APIService.swift:

The above shown gist has the necessary generic methods to handle GET and POST requests.

Now comes the part where we perform network requests.

Note: I’ve added network requests code in the ViewController.swift class. Put that on ViewModel or Presenters provided that you’ve used some architecture in your application.

GET Request:

The above code can be described as:

  1. First, we safely unwraps the URL from the string variable named getURLString (provide your own URL String)
  2. Second, the loading is shown.
  3. Finally, we use the singleton instance of APIService to perform GET request. The getRequest requires url, type is the model class that conforms to Codable which our APIService will cast the response to model class. It has completionHandler and errorHandler for handling the success or failure cases.

Now that we’ve got our response we can use it anyway we prefer.

POST Request:

For performing POST request, I’ve used https://jsonplaceholder.typicode.com/guide.html. It helps developers to play with fake API responses.

The above code can be described as:

  1. First, we safely unwraps the URL from the string variable named postURLString (provide your own URL String)
  2. Second, the loading is shown.
  3. Finally, we use the singleton instance of APIService to perform POST request. The postRequest requires url, type is the model class that conforms to Codable which our APIService will cast the response to model class. We also have to provide params for POST request. It also has completionHandler and errorHandler for handling the success or failure cases.

In this way, we can manage our Network request code rather than re-writing network request code in every API request using Generics.

If you want the demo project, you can get it at https://github.com/nabs107/GenericsApiService

Please star the project if it helped you in anyway.

Feel free to provide any improvements that can be done in the article.

--

--