[SalesForce] Use of Wildcard in Apex rest service

I have been using rest service and building them for long time but something which I am not clear is on the wildcard part.
Whenever I had to expose an Apex rest service I expose apex class with annotation like – @RestResource(urlMapping='/Cases/*'). I do put '*' at the end of
the URL , but I haven't discovered the use case for that.

Recently I just tried to build a REST service to understand the wildcard application:

@RestResource(urlMapping='/Cases/*')
global with sharing class CaseManager {

    @HttpPost
    global static ID createCase(String subject, String status,
        String origin, String priority) {
        Case thisCase = new Case(
            Subject=subject,
            Status=status,
            Origin=origin,
            Priority=priority);
        insert thisCase;
        return thisCase.Id;
    }   

}

I use workbench to test the above rest service by trying to create a Case record. I tried calling the apex service and used a JSON wiht POST method to create cases. All of the below URI worked to create a CASE using the service:

  1. /services/apexrest/Cases/cheese
  2. /services/apexrest/Cases/Dog
  3. /services/apexrest/Cases/man

I know since it is wildcard it can take any value for '*', but what is the significance of using different name for the wildcard when all of them does
the same job of creating a CASE record. Please enlighten me with an example if possible.

Best Answer

If you don't use a wildcard, you need an exact match (e.g. /services/apexrest/Cases will work, but /services/apexrest/Cases/Dog will not). If you do use a wildcard, you can use the contents of the URL for additional information, such as /services/apexrest/UpdateCase/500300000012345.

You can even use wildcards in the middle of the URL, such as /services/apexrest/Cases/500300000012345/Update, if you want to use a RESTful pattern. The requested URL will appear in RestContext.request.requestURI, which you can then parse by splitting as a string (requestURI.split('/')), or by using a Pattern, or any other method you might want to use.

Just be aware that using when using URLs with and without wildcards, that the request will be sent to the most precise URL; if you have the URLs /Cases/*/ and /Cases/Update/, then Update will be used when it is specified, and the /Cases/*/ will be used otherwise.

Related Topic