Search code examples
resourcesclientballerina

Undefined resource path when using a number in the client resource access path


When having the following sample ballerina client:

public client class SimpleClient {
    resource function get metadata/[string id]() returns string {
        return "";
    }
}

and calling it like: sampleClient->/metadata/123()

I get the error undefined resource path in object. To get this to work I had to explicitly cast it to string: sampleClient->/metadata/[string `123`]

Is there a better solution to handle this scenario? I don't really understand why the type is not inferred.


Solution

  • The issue here is ballerina does not directly allow numeric literals as a resource path segment. Things that are allowed as resource path segments are:

    1. Resource path segment name:= An identifier eg: metadata
    2. Computed resource access path segment:= [expression]
    3. Resource access rest segment:= [spread]

    Since 123 is not an identifier, sampleClient->/metadata/123() will be invalid syntax and you should get syntax errors. Because of the target resource segment type is string we can do the following to fix the issue.

    1. Use quoted identifier which allows to write numbers as identifiers := simpleClient->/metadata/'123;
    2. Use computed resource access path segment to pass 123 as a string:= simpleClient->/metadata/["123"];. Note: If you do simpleClient->/metadata/[123];, 123 will be considered as int