Introduction to Path and Query Parameters in Swift

Introduction to Path and Query Parameters

Welcome to another lesson in this course. In our previous lessons, we established a foundation by learning about RESTful APIs and making GET requests using Swift's URLSession. Now, we will shift our focus to path and query parameters, essential tools for refining API requests and fetching specific data.

Path and query parameters play a crucial role in making your API requests more precise and efficient. Imagine you are shopping online: selecting a specific item using its ID is akin to a path parameter, while filtering items by categories like price or color resembles query parameters. In this lesson, we'll explore these concepts with practical examples, empowering you to extract just the information you need from an API.

Understanding Path Parameters

Path parameters are part of the URL used to access specific resources within an API, acting as unique identifiers. For example, if you want to retrieve a to-do item with ID 3, the URL would be structured as follows:

http://localhost:8000/todos/3

In this case, 3 is the path parameter specifying the particular item you wish to access.

Fetching Data with Path Parameters

Path parameters allow you to target specific resources within an API, enabling direct access to individual items. In Swift, we use URLSession to send requests. Here's how you can fetch details of a specific to-do item using its ID:

import Foundation
import FoundationNetworking

let dispatchGroup = DispatchGroup()
dispatchGroup.enter()

let todoId = 3
let urlString = "http://localhost:8000/todos/\(todoId)"

if let url = URL(string: urlString) {
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        defer { dispatchGroup.leave() }

        if let error = error {
            print("Error fetching the todo: \(error)")
            return
        }
        
        guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
            print("Error fetching the todo with path parameter")
            if let httpResponse = response as? HTTPURLResponse {
                print("Status Code: \(httpResponse.statusCode)")
            }
            return
        }
        
        if let data = data {
            do {
                let todo = try JSONDecoder().decode(Todo.self, from: data)
                print("ID: \(todo.id)")
                print("Title: \(todo.title)")
                print("Description: \(todo.description)")
                print("Done: \(todo.done)")
            } catch {
                print("Error decoding JSON: \(error)")
            }
        }
    }
    task.resume()
    dispatchGroup.wait()
}

struct Todo: Codable {
    let id: Int
    let title: String
    let description: String
    let done: Bool
}

In this code, the todoId is a path parameter specifying the to-do item with ID 3, forming the URL http://localhost:8000/todos/3. Upon success, you'll see details of the to-do item, illustrating how path parameters enable precise resource access.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal