Path Variable and Query Params

Jerry PM
3 min readMay 6, 2024

--

And how to handle in Swift Code

Source: Author

In the context of Postman, “Path Variables” and “Query Params” are used to send data to a specific endpoint in an HTTP request. Here’s the difference:

1. Path Variables:

  • Path Variables are part of the URL used to identify a specific resource.
  • They are inserted into the URL and are enclosed in curly braces {}.
  • Path Variables are used to convey information such as entity IDs, usernames, etc.
  • Example: /users/{userId}. Here, {userId} is a path variable that will be replaced with the corresponding value when the request is sent.

2. Query Params:

  • Query Params are part of the URL used to add parameters to an HTTP request.
  • They start after the question mark (?) in the URL and are separated by & if there's more than one parameter.
  • Query Params are typically used for filtering, sorting, and other optional parameters.
  • Example: /users?role=admin&status=active. Here, role and status are query parameters.

In Postman, you can easily add and send Path Variables and Query Params in an HTTP request. For Path Variables, you can set them in the Path section of the request. Whereas for Query Params, you can add them in the Params section of the request.

This is how to handle the difference of them for swift code

import Alamofire

// Example of using Path Variables
let userId = 123
let urlWithPathVariable = "https://example.com/users/\(userId)"

AF.request(urlWithPathVariable).responseJSON { response in
switch response.result {
case .success(let data):
print("Response: \(data)")
case .failure(let error):
print("Error: \(error)")
}
}

// Example of using Query Params
let parameters: [String: Any] = [
"role": "admin",
"status": "active"
]
let urlWithQueryParams = "https://example.com/users"

AF.request(urlWithQueryParams, parameters: parameters).responseJSON { response in
switch response.result {
case .success(let data):
print("Response: \(data)")
case .failure(let error):
print("Error: \(error)")
}
}

n this Swift code snippet, I’ve provided examples of using “Path Variables” and “Query Params” with Alamofire to make HTTP requests. The comments in the code explain each example. Make sure to replace "https://example.com" with the appropriate URL for your endpoint.

Transform Your Ideas into Reality with Expert iOS & Flutter Development! 🚀 Are you looking to bring your app concept to life? I specialize in crafting exceptional iOS and Flutter applications that stand out in the digital world. Let’s collaborate to turn your vision into a stunning, functional app. Contact me today to start your app development journey!”

Hire me -> https://www.upwork.com/freelancers/~01b22fa418e8c595b9

--

--

No responses yet