[SalesForce] Is it possible to have multiple POST calls in the same Apex REST class

I have a requirement to write a REST class to fetch different set of resources that need to be accessed through different endpoints.
Eg.

  • /services/apexrest/abc/contractors
  • /services/apexrest/abc/departments

Both the calls have to be POST calls as we need to send some details in request body. I read some QnA articles mentioning there can be only one @HttpPost method per class. (https://developer.salesforce.com/forums/?id=906F00000009DiDIAU)

But is there any alternate way to write a single apex class that can handle multiple POST calls ?

Best Answer

You're free to write your resource as:

@RestResource(urlMapping='/abc/*')

Where * indicates a wildcard; this will match any resource that matches this wildcard pattern.

From here, you can then dispatch various methods:

@HttpPost global static void doPost() {
  switch on RestContext.request.requestURI.substringAfterLast('/')) {
    when 'contractors' { doContractorPost(); }
    when 'departments' { doDepartmentsPost(); }
    when else { doInvalidCall(); }
  }
}

What you do from here is up to you. It's just code.