Fetch Data From API Using URLSession

This article contains simple demo on how to fetch data from API using URLSession in Swift Programming Language.


  1. MacOS
  2. XCode
  • Open XCode. Select File -> New -> Playground. Select iOS -> Blank file. Name and save it to a desired location.

  • In this demo, we will be fetching the data from a dummy API. The URL endpoint that we will be using is https://jsonplaceholder.typicode.com/posts. You can use Postman to check if the endpoint works or not.
  • So, let's begin by creating a struct that conforms to the Codable Protocol.
  • Codable protocol is a type alias for Encodable and Decodable protocols. Encodable protocol is used to convert data into external representation such as JSON whereas Decodable protocol is used to convert external representation data into the data that we need.
    NOTE: Make sure all the names of the variables match with the keyword used in the JSON in the URL link. Also, match the data types according to the values used in the JSON data.
    struct Post: Codable {
    // The names of the variables should match with the keys used in the link. Also, the data types should match with the values of the URL link.
        let userId: Int
        let id: Int
        let title: String
        let body: String
  • Now, let's create a request to call the API. For that, we will be using the URLRequest.
  • URLRequest creates a URL request with the given URL, cache policy and timeout interval.
  • In the playground, add the following code: 
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    var request = URLRequest(url: url)
    request.httpMethod = "GET"  // optional
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  • In the above code, since we are fetching the data from API, we are providing the httpMethod as GET.
  • If you need to create and send any data to API, at that time the httpMethod will be POST. By default, the httpMethod will be GET. Hence, line number 3(as per above code) is optional.
  • Now, we will be using dataTask of URLSession to retrieve the contents of the URL. 
  • URLSession is an object that coordinates a group of related network data transfer tasks. The URLSession class and related classes provide an API by downloading and uploading data to endpoints indicated by URL.
  • 'shared' is a shared singleton session object to fetch contents of URL to memory using few lines of code.
  • 'dataTask' is used to retrieve contents of URL based on specified URL request object and calls a handler upon completion.
  • Add the following code:
    let task = URLSession.shared.dataTask(with: request){ data, response, error in
        if let error = error {
            print("Error while fetching data:", error)
        guard let data = data else {
  • In the above code, 'data' contains the contents of the URL in the JSON format. 'response' will give you the response code and 'error' is used to display errors occured if any.
  • Since the data fetched is in the JSON format, we will have to decode it. For that, we will be using JSONDecoder.
  • JSONDecoder is used to decode instances of data type from JSON objects.
  • Add the below code after line number 9 (line as per above code).
    do {
            let posts = try JSONDecoder().decode([Post].self, from: data) // Since the JSON in the URL starts with array([]), we will be using [Post].self. If the JSON starts with curly braces ({}), use Post.self
            // Fetching each element from array
            for post in posts {
                print("User ID:", post.userId)
                print("Id:", post.id)
                print("Title:", post.title)
                print("Body:", post.body)
        } catch let jsonError {
            print("Failed to decode json", jsonError)
    NOTE: The JSON in the URL starts with an array, i.e. [ ]. Hence we are passing the data type as an array of the struct, i.e [Post].self to the decode method of JSONDecoder. If the JSON starts with curly braces { }, then we will be passing the data type as Struct directly, i.e. Post.self.
  • At last, add the following line of code.
  • 'resume()' is important to start the data task as well as to start the tasks if they are suspended. The above code won't run if this line of code is missed.
  • We are done! Run the Playground. If everything goes well, you must see the data in the console of the Playground.

Similar Articles