How to Fetch JSON Data from APIs in SwiftUI
Tags: swift, ios, swiftui
Published: 2021-01-11 18:24:43

---
title: How to Fetch JSON Data from APIs in SwiftUI
published: true
description: 
tags: #swift #ios #swiftui
//cover_image: https://direct_url_to_image.jpg
---
<!-- wp:paragraph -->
<p>In this post we are going to take a look at how we can get JSON data from an API and show it in a list view in SwiftUI. Let's jump right in a get started by creating a new SwiftUI project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In this project we are going to be using the <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> API. <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> is a free to use fake <strong>REST API</strong> for testing and prototyping. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We will be fetching our data from the <strong><em>https://jsonplaceholder.typicode.com/posts/1/comments</em></strong> URL.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now in our Xcode project we will create a model file and name it <strong>Comments</strong>. This will be our model for the data we are going to want to show in our list view.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import SwiftUI

struct Comments: Codable, Identifiable {
    let id = UUID()
    let name: String
    let email: String
    let body: String
    
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In the code above we made a simple struct that conforms to the <a href="https://developer.apple.com/documentation/swift/codable">Codable</a> and <a href="https://developer.apple.com/documentation/swift/identifiable">Identifiable</a> protocols. <a href="https://developer.apple.com/documentation/swift/codable">Codable</a> is used for decoding and encoding the JSON data we get from our API call. <a href="https://developer.apple.com/documentation/swift/identifiable">Identifiable</a> is used to help us make a unique identifier for our <strong>Comments</strong> object so our app can keep track of it. In our example it helps us to keep track of our comments and display them in the right order for our list view. We also have added the <strong>name</strong>, <strong>email</strong>, and <strong>body</strong> properties that will be set to the JSON data we get back from our API call.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next we will add a new file where we will create the call to our API to get our JSON data. Let's start by creating a new file and naming it <strong>commentViewModel</strong>. Then we will add the following code to our <strong>commentViewModel</strong> file.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import Foundation

class apiCall {
    func getUserComments(completion:@escaping (&#91;Comments]) -&gt; ()) {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1/comments") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let comments = try! JSONDecoder().decode(&#91;Comments].self, from: data!)
            print(comments)
            
            DispatchQueue.main.async {
                completion(comments)
            }
        }
        .resume()
    }
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Above all we did was create a class called <strong>apiCall</strong> and added a function called <strong>getUserComments()</strong>. In our <strong>getUserComments()</strong> function we first make a <strong>guard let</strong> statement on our <strong>url</strong> variable. This is to check to make sure we have a valid URL otherwise the function will stop there and not execute the rest of the code. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next we use <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a> to make our call to get the data from the URL. Inside of our <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a> closure we create a new variable called <strong>comments</strong> and we assign the decoded JSON to our variable. Then we use <strong><a href="https://developer.apple.com/documentation/dispatch/dispatchqueue">DispatchQueue</a></strong> to make sure we are running this API call on the main thread and not a background thread of our app. On completion of retrieving our data we then assigns the data to our comments variable. Lastly we can't forget the <strong>.resume()</strong> function at the end of your <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a> curly brace. If you forget this the function will never run the API call to the URL.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now that we have our view model setup lets go into <strong>ContentView</strong> file and add the following code to our file. </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import SwiftUI

struct ContentView: View {
    //1.
    @State var comments = &#91;Comments]()
    
    var body: some View {
        NavigationView {
            //3.
            List(comments) { comment in
                VStack(alignment: .leading) {
                    Text(comment.name)
                        .font(.title)
                        .fontWeight(.bold)
                    Text(comment.email)
                        .font(.subheadline)
                        .fontWeight(.bold)
                    Text(comment.body)
                        .font(.body)
                }
                
            }
            //2.
            .onAppear() {
                apiCall().getUserComments { (comments) in
                    self.comments = comments
                }
            }.navigationTitle("Comments")
        }
    }
}</code></pre>
<!-- /wp:code -->

<!-- wp:list {"ordered":true} -->
<ol><li>First we created a <strong>@State</strong> variable that takes in an array of our <strong>Comments</strong> model.</li><li>Next we added the <strong>.<a href="https://developer.apple.com/documentation/swiftui/text/onappear(perform:)">onAppear</a>()</strong> function. This is were we make our call to our API to get our data and then set it to the <strong>comments</strong> variable we just created.</li><li>Then in our list view we pass in the data that we have in our <strong>Comments</strong> array</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>  Now we can go and run our app. We should see something like the image below.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":1403,"width":292,"height":632,"sizeSlug":"large","linkDestination":"none"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://swifttomcom.files.wordpress.com/2021/01/simulator-screen-shot-iphone-12-pro-2021-01-08-at-16.39.36.png?w=473" alt="" class="wp-image-1403" width="292" height="632"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Thats all we need to fetch and show JSON data in SwiftUI. Thanks for reading!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Happy Coding! </p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://media2.giphy.com/media/4FQMuOKR6zQRO/giphy.gif?cid=ecf05e47eve0t94gcjgizod66y2n5j54arndqtk30lp9cibk&amp;rid=giphy.gif" alt="data numbers GIF"/></figure></div>
<!-- /wp:image -->