REST regular expressions


REST Regular Expressions

REST URI Resources can be expressed with Regular expression on @PathParam.

  • The @Path annotation supports the use of template parameters as :{ name : regex }.
  • The template parameter name is required.The colon (:) followed by a regular expression is optional and will default to the pattern: [^/]+
  • Multiple template parameters may be defined in a single @Path.
  • Template parameter values will be injected into method parameters annotated with @PathParam.

REST Regular expressions Examples:

  • @Path(“product/{code: [a-zA-Z][a-zA-Z_0-9]*}”) –  code variable should match  one upper or lower case letter and zero or more alpha numeric characters and the underscore character.
  • @Path(“categories/{id}:.*”}  – would match any id
  • @Path(“/get-students/{sid: \\d{5}}”)   – SID value should be 5 digit
  • As shown in the below is code that expressed as Regular Expressions is that sid is constrained to 5digits:
    • http://localhost:8080/rest-example/rest/student/get-students/10938Valid REST URL
    • http://localhost:8080/rest-example/rest/student/get-students/234Return 404 Error
@Path("/student")
public class StudentResource {
@GET
@Path("/get-students/{sid: \\d{5}}")
@Produces("text/plain")
public String getStudents(@PathParam("sid") int sid) {
return "Your id is: " + sid;
}

Leave a Reply