[SalesForce] Apex rest HttpGet Method help

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;



    }
}

Best Answer

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
                        ];
    }
}
Related Topic