Tutorial 15: Fetching and Displaying JSON Data from a REST API in Swift
Introduction In this tutorial, we will learn how to fetch and display JSON data from a REST API in Swift. We will build a simple Gaming Leaderboard app that fetches player rankings from a mock API and displays them in a SwiftUI list. By the end of this tutorial, you will understand how to: Make network requests in Swift using URLSession Parse JSON data into Swift models using Codable Display data dynamically in a SwiftUI List Handle errors and optimize API calls Step 1: Setting Up the Project Open Xcode and create a new SwiftUI App project. Name the project GamingLeaderboard and make sure SwiftUI is selected. Step 2: Creating the JSON API For this tutorial, we'll use a mock API service such as jsonplaceholder.typicode.com or mockapi.io. However, for simplicity, let's assume our API URL is: https://example.com/api/leaderboard The API returns JSON data like this: [ {"id": 1, "name": "PlayerOne", "score": 1200}, {"id": 2, "name": "GamerX", "score": 1100}, {"id": 3, "name": "Legend99", "score": 1050} ] Step 3: Creating the Data Model We need a Swift model to map the JSON data. Create a new Swift file named Player.swift and define the structure: import Foundation struct Player: Codable, Identifiable { let id: Int let name: String let score: Int } Codable allows us to parse JSON into this model automatically. Identifiable helps us use this in SwiftUI lists. Step 4: Fetching JSON Data Create a new Swift file LeaderboardViewModel.swift and add the following code: import Foundation class LeaderboardViewModel: ObservableObject { @Published var players: [Player] = [] func fetchLeaderboard() { guard let url = URL(string: "https://example.com/api/leaderboard") else { return } URLSession.shared.dataTask(with: url) { data, response, error in if let data = data { do { let decodedData = try JSONDecoder().decode([Player].self, from: data) DispatchQueue.main.async { self.players = decodedData } } catch { print("Error decoding JSON: \(error.localizedDescription)") } } else if let error = error { print("Network error: \(error.localizedDescription)") } }.resume() } } @Published ensures the UI updates when new data arrives. fetchLeaderboard() makes an API call and updates the players array. Step 5: Building the SwiftUI Interface Open ContentView.swift and modify it as follows: import SwiftUI struct ContentView: View { @StateObject var viewModel = LeaderboardViewModel() var body: some View { NavigationView { List(viewModel.players) { player in HStack { Text(player.name) .font(.headline) Spacer() Text("Score: \(player.score)") .font(.subheadline) .foregroundColor(.gray) } .padding() } .navigationTitle("Gaming Leaderboard") .onAppear { viewModel.fetchLeaderboard() } } } } Step 6: Running the App Run the project in Xcode. Ensure the data loads when the app launches. If the API doesn't work, try using a mock API like mockapi.io. Step 7: Enhancements & Next Steps To further improve the app, consider: Adding pull-to-refresh functionality. Implementing error handling with user alerts. Caching API responses for offline viewing. Sorting players based on scores dynamically. Conclusion In this tutorial, we built a Gaming Leaderboard app that fetches JSON data from an API and displays it in SwiftUI. We covered: Making network requests using URLSession Parsing JSON with Codable Using @StateObject to manage data Displaying data in a List Now, you can extend this project by adding animations, a search feature, or even integrating Firebase for real-time updates!

Introduction
In this tutorial, we will learn how to fetch and display JSON data from a REST API in Swift. We will build a simple Gaming Leaderboard app that fetches player rankings from a mock API and displays them in a SwiftUI list. By the end of this tutorial, you will understand how to:
- Make network requests in Swift using
URLSession
- Parse JSON data into Swift models using
Codable
- Display data dynamically in a SwiftUI
List
- Handle errors and optimize API calls
Step 1: Setting Up the Project
- Open Xcode and create a new SwiftUI App project.
- Name the project
GamingLeaderboard
and make sure SwiftUI is selected.
Step 2: Creating the JSON API
For this tutorial, we'll use a mock API service such as jsonplaceholder.typicode.com
or mockapi.io
. However, for simplicity, let's assume our API URL is:
https://example.com/api/leaderboard
The API returns JSON data like this:
[
{"id": 1, "name": "PlayerOne", "score": 1200},
{"id": 2, "name": "GamerX", "score": 1100},
{"id": 3, "name": "Legend99", "score": 1050}
]
Step 3: Creating the Data Model
We need a Swift model to map the JSON data. Create a new Swift file named Player.swift
and define the structure:
import Foundation
struct Player: Codable, Identifiable {
let id: Int
let name: String
let score: Int
}
-
Codable
allows us to parse JSON into this model automatically. -
Identifiable
helps us use this in SwiftUI lists.
Step 4: Fetching JSON Data
Create a new Swift file LeaderboardViewModel.swift
and add the following code:
import Foundation
class LeaderboardViewModel: ObservableObject {
@Published var players: [Player] = []
func fetchLeaderboard() {
guard let url = URL(string: "https://example.com/api/leaderboard") else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let decodedData = try JSONDecoder().decode([Player].self, from: data)
DispatchQueue.main.async {
self.players = decodedData
}
} catch {
print("Error decoding JSON: \(error.localizedDescription)")
}
} else if let error = error {
print("Network error: \(error.localizedDescription)")
}
}.resume()
}
}
-
@Published
ensures the UI updates when new data arrives. -
fetchLeaderboard()
makes an API call and updates theplayers
array.
Step 5: Building the SwiftUI Interface
Open ContentView.swift
and modify it as follows:
import SwiftUI
struct ContentView: View {
@StateObject var viewModel = LeaderboardViewModel()
var body: some View {
NavigationView {
List(viewModel.players) { player in
HStack {
Text(player.name)
.font(.headline)
Spacer()
Text("Score: \(player.score)")
.font(.subheadline)
.foregroundColor(.gray)
}
.padding()
}
.navigationTitle("Gaming Leaderboard")
.onAppear {
viewModel.fetchLeaderboard()
}
}
}
}
Step 6: Running the App
- Run the project in Xcode.
- Ensure the data loads when the app launches.
- If the API doesn't work, try using a mock API like
mockapi.io
.
Step 7: Enhancements & Next Steps
To further improve the app, consider:
- Adding pull-to-refresh functionality.
- Implementing error handling with user alerts.
- Caching API responses for offline viewing.
- Sorting players based on scores dynamically.
Conclusion
In this tutorial, we built a Gaming Leaderboard app that fetches JSON data from an API and displays it in SwiftUI. We covered:
- Making network requests using
URLSession
- Parsing JSON with
Codable
- Using
@StateObject
to manage data - Displaying data in a
List
Now, you can extend this project by adding animations, a search feature, or even integrating Firebase for real-time updates!