Home > OS >  How to construct URL with repeating query keys?
How to construct URL with repeating query keys?

Time:03-13

I have to construct such URL "myapi?category=69&filters[pa_ram]=83,84&filters[pa_storage]=79"

I tried to build in Playground first using URLQueryItem and URLComponents

func callApi(categoryID: String, paramName: String, paramVal: String) {

let queryItems = [URLQueryItem(name: "category", value: categoryID), URLQueryItem(name: "filters[\(paramName)]", value: paramVal)]
var urlComps = URLComponents(string: "myapi")!
urlComps.queryItems = queryItems
let result = urlComps.url!
print(result)

}

callApi(categoryID: "69", paramName: "pa_ram", paramVal: "84")

But I'm getting wrong URL "myapi?category=69&filters[pa_ram]=84" and also can't understand how should I construct API with repeating query keys. I would appreciate any help.

CodePudding user response:

To support multiple filters I would use a Dictionary instead to pass the filter parameters to the function

func callApi(categoryID: String, parameters: [String: String]) -> URL {
    var queryItems = [URLQueryItem(name: "category", value: categoryID)]
    for parameter in parameters {
        queryItems.append(URLQueryItem(name: "filters[\(parameter.key)]", value: parameter.value))
    }
    var urlComps = URLComponents(string: "myapi")!
    urlComps.queryItems = queryItems
    return urlComps.url!
}

Note that a dictionary is unordered so if the order is important you could use a custom struct instead and pass an array of it.

To use brackets I would simply do a search and replace of the url string

let url = callApi(categoryID: "69", parameters: ["pa_ram": "84", "pa_storage": "79"])
let fixed = url.absoluteString
    .replacingOccurrences(of: "[", with: "[")
    .replacingOccurrences(of: "]", with: "]")
  • Related