0

How can i make it that for example I inputted /services/apexrest/Account/0016F00001sYSFQ it will show that certain record but if I type /services/apexrest/Account it will show all the records of that account.

This is using HttpGet request in apex class

This is my code so far

@RestResource(urlMapping='/Account/*')
global with sharing class AccountManager {

    @HttpGet
    global static Account getAccountId() {
        RestRequest request = RestContext.request;
        // grab the caseId from the end of the URL
        String accountId = request.requestURI.substring(
          request.requestURI.lastIndexOf('/')+1);



        Account result =  [SELECT Name,BillingStreet,BillingCity,BillingCountry,Phone
                        FROM Account
                        WHERE Id = :accountId
                        ];
        return result;



    }
}
  • Probably you can create two different API. One for getAccountById and 2nd getAllAccount – RCS Jan 23 '17 at 9:03
  • Can you do a system.debug and check what are you getting for 'accountId' when you hit '/Account' and '/Account/xxxxxx'. I guess in the first case you will be getting 'Account' and not any Id. Then you can put an if condition on this. Change you method return type to List<Account>. – Saumya Ranjan Satapathy Jan 23 '17 at 10:54
2

You probably want to create two classes. Simply because you return is a single account if the Id is specified but you return a list when you run your query without the where clause.

Alternatively, you can always return a list and just change your query. See the example below:

@RestResource(urlMapping='/Account/*')
global with sharing class AccountManager {

    @HttpGet
    global static List<Account> getAccountS() {
        RestRequest request = RestContext.request;
        // grab the caseId from the end of the URL
        String accountId = request.requestURI.substring(
          request.requestURI.lastIndexOf('/')+1);

If(accountId != null){

        return  [SELECT Name,BillingStreet,BillingCity,BillingCountry,Phone
                        FROM Account
                        WHERE Id = :accountId
                        ];
} else {
        return  [SELECT Name,BillingStreet,BillingCity,BillingCountry,Phone
                        FROM Account
                        ];
    }
}
| improve this answer | |
  • Hi @JannisBott I don't think you can create two HttpGet Method. – JMDF Jan 23 '17 at 10:31
  • Good point. I'll edit the answer – Jannis Bott Jan 23 '17 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.