How to include special characters like "-" in a resource path of a ballerina service

79 views Asked by At

My requirement is to create an endpoint for /school/{student-id}. I tried the below code.


service /school on new http:Listener(9000) {
    resource function get student/[string student\-id]() returns Student? {
        return studentTable[student\-id];
    }
}

public type Student record {|
    readonly string student\-id;
    string name;
    int age;
|};

public final table<Student> key(student\-id) studentTable = table [
    {student\-id: "333X", name: "Ross", age: 15},
    {student\-id: "465Q", name: "Kyle", age: 16}
];

I am getting error: service registration failed: Invalid character: '\' in expression for the above code.

How can I get the student-id to work as the resource path parameter?

1

There are 1 answers

0
LochanaJ On BEST ANSWER

Well, the code written above is correct. The error is due to a bug in older versions of ballerina. However, the bug seem to be fixed for versions above ballerina swan-lake 2201.6.0

There's another way you can include special characters. Here 002D is the unicode code point for -. This works with the versions below 2201.6.0 as well. e.g.

resource function get student/[string student\u{002D}id]() returns Student? { }

In a nutshell, you can use either backslash(\) or unicode numeric escape(\u{xxxx}) to include special characters in the resource path or any identifier defined in ballerina.

Sample endpoint implementations:

  1. GET /school/{student-id}
service /school on new http:Listener(9000) {
    resource function get student/[string student\-id]() returns Student? {
        // logic goes here
    }
}

or

service /school on new http:Listener(9000) {
    resource function get student/[string student\u{002D}id]() returns Student? {
        // logic goes here
    }
}
  1. GET /school/student-performance
service /school on new http:Listener(9000) {
    resource function get student\-performance() returns StPerformance[] {
        // logic goes here
    }
}

or

service /school on new http:Listener(9000) {
    resource function get student\u{002D}performance() returns StPerformance[] {
        // logic goes here
    }
}