12

In Apex RestResource What is the correct format for urlMapping when you want to pass in multiple parameters in a GET request? So I need to pass in accountId and serviceId as filters to GET.

@RestResource(urlMapping='/Revenues/accountId={acctId}&serviceId={svcId}');

OR

@RestResource(urlMapping='/Revenues/accountId/*/serviceId/*');

I am confused. I tried to use the first one and then get the parameterss using request.params.get('accountId'); but just get NULL.

2 Answers 2

16

HTTP GET defines data as a series of query parameters in the URI itself. For example, here’s a URI:

https://na8.salesforce.com/services/apexrest/FieldCase?companyName=GenePoint

So your code will be like

@RestResource(urlMapping='/Revenues/*)
@HttpGet
  global static List<Case> getOpenCases() {
    String accountId = RestContext.request.params.get('accountId');
    String serviceId = RestContext.request.params.get('serviceId');

Creating REST APIs using Apex REST

Or you can parse the URl as well

@HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

Apex REST Basic Code Sample

2

Honestly, and it's Salesforce's fault, I think the answers to your question are going to suck.

You SHOULD be able to do this:

@RestResource(urlMapping='/Revenues/account/{accountId}/service/{serviceId}');

... but the Apex annotation doesn't let you. It'd be neat though, right?

The "accepted" answer is as close as you're gonna get. For the parse-based method, perhaps a Regex-based mechanism (helper method) could more easily pull out those IDs from a well-formed URI? I.e. given a Dictionary with keys and empty values, and a URI, pull out the values?

It may seem overly-complicated, but if you start writing lots of APIs, the copy-pasting of the same Substring/LastIndexOf code over and over it going to feel tedious.

2
  • 7
    If your code is feeling repetitive and tedious, you should have written a utility long ago. Commented Aug 21, 2018 at 16:14
  • 3
    And yet, the route pattern I declared it should be, is straight out of Java and .NET. One should not have to write a utility, because the problem should not exist. And if they followed a RegEx way, then surely it'd be in a helper/utility (because who wouldn't do that?!) Commented Sep 12, 2018 at 20:54

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.