Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Square brackets in query parameters #2950

Closed
RussBaz opened this issue Feb 3, 2023 · 1 comment
Closed

Square brackets in query parameters #2950

RussBaz opened this issue Feb 3, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@RussBaz
Copy link
Contributor

RussBaz commented Feb 3, 2023

If I send a request with the following query parameters:

?a[]=1&a[]=2

I get:

key: "a", value: ["1", "2"]

However, if I send ?a[b]=1&a[b]=2

I get key: "a", value: []

Replacing [ and ] with %5B and %5D makes no difference.

Furthermore, ?a[b]c=1 results in an exception "Malformed form-urlencoded key encountered: a[b]c"

  1. Can you clarify if this is an intended behaviour?

I personally would like to parse ?a[b]=1&a[b]=2&a[c]=3 into

key: "a[b]", value ["1", "2"]
key: "a[c]", value: ["3"]
  1. Is there a way to achieve what I want?

Here is the test Content struct:

struct RandomFilter: Content {
    private struct DynamicCodingKeys: CodingKey {
        var stringValue: String
        
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        
        var intValue: Int?
        
        init?(intValue: Int) {
            return nil
        }
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
        
        for key in container.allKeys {
            let value = try container.decode([String].self, forKey: key)
            
            print("key: \"\(key.stringValue)\", value: \(value)")
        }
    }
}

Thank you.

@RussBaz RussBaz added the enhancement New feature or request label Feb 3, 2023
@0xTim
Copy link
Member

0xTim commented Apr 11, 2023

I don't think there's a way to achieve what you want and this is probably expected behaviour. Since [ and %5B are effectively the same thing when it comes to a query parameters there's no way for us to 'escape' the bracket so we need to treat a[b] as a dictionary with a key rather than the key itself. Dictionaries are a pain in URL queries so Vapor needs to make a decision somewhere and this is the line we've drawn unfortunately.

I'll close this but feel free to ask more questions or reopen if you think there's a better solution

@0xTim 0xTim closed this as not planned Won't fix, can't repro, duplicate, stale Apr 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants