Simple Async API Request With Swift 5 Result Type in SwiftUI

Omer Rahmanovic
Mac O’Clock
Published in
3 min readOct 17, 2020

--

In this article we will go quickly through async API request using Apple provided Swift 5 Result Type. For this example we will use REST Countries API (https://restcountries.eu/rest/v2/all) so you don’t need API key or anything it is completely free.

Before we do anything let’s have a look at our API response in Postman

API Response

As you can see from this screenshot our API is returning to us an array of countries with it’s data in {…}.

So let’s look at what will we use in our app from single country data.

Single country API response

From this response we are going to use only name of country and population.

First thing to do is making our model which will be parsed later on.

Country model

Notice that we are not going to use all data from API response but just the data we want to show in our app. In this case only name and population.

After creating our model we are going to define our network call to get data from the API. So for this purpose it is good to create separate .swift file just for network calls.

API call

Here we are making our API call function where it will fetch data from the web using Swift’s result type, so first thing we provided is URL and if it is ok we can decode JSON as shown. If successful it will on completion return list of countries if not error will be presented in our console. Most of the errors in this part are linked to our model so pay attention while making models based on JSON response.

Extension on ContentView()

So finally we are going to present our data on the ContentView() but before we do it I suggest you to make an extension of View where are you going to make api call just for the better organisation but it is no necessary because you can make this call in .onAppear() as i will show you next.

Fetch data and assign in to @State variable

So as you can see we made our API call in .onAppear() method and assigned values to our State variable countries. Last thing we need to do is presenting data on the View.

Data presented on the View

I just want to said that in this tutorial i was not going through details about Result Type and main goal of this article is to show how to make API call as simple as possible.

Hope it helps you. If you have any questions or problems regarding this topic be free to ask in the comment and i will try to solve those issues with you.

--

--