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;



    }
}
2
  • Probably you can create two different API. One for getAccountById and 2nd getAllAccount
    – RCS
    Jan 23, 2017 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>. Jan 23, 2017 at 10:54

1 Answer 1

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
                        ];
    }
}
2
  • Hi @JannisBott I don't think you can create two HttpGet Method.
    – JMDF
    Jan 23, 2017 at 10:31
  • Good point. I'll edit the answer Jan 23, 2017 at 10:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .