Create an Apex REST service that returns an account and it's contacts.
To pass this challenge, create an Apex REST class that is accessible at '/Accounts/<Account_ID>/contacts'. The service will return the account's ID and Name plus the ID and Name of all contacts associated with the account. Write unit tests that achieve 100% code coverage for the class and run your Apex tests.
- The Apex class must be called 'AccountManager'.
- The Apex class must have a method called 'getAccount' that is annotated with @HttpGet
- The method must return the ID and Name for the requested record and all associated contacts with their ID and Name.
- The unit tests must be in a separate Apex class called 'AccountManagerTest'.
- The unit tests must cover all lines of code included in the AccountManager class, resulting in 100% code coverage.
- Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.
AccountManager Class:
@RestResource(urlMapping='/Accounts/*/contacts')
global class AccountManager {
@HttpGet
global static Account getAccount(){
RestRequest request = RestContext.request;
String accountId = request.requestURI.substringBetween('Accounts/','/contacts');
Account Result = [SELECT Id, Name, (SELECT Id, Name From Contacts) From Account Where Id =: accountId];
system.debug('Result is :' +Result);
Return Result;
}
}
AccountManagerTest Class:
@isTest
private class AccountManagerTest {
private static testMethod void testGetAccount(){
Id recordId = createTestRecord();
RestRequest request = new RestRequest();
request.requestUri = 'https://na35.salesforce.com/services/apexrest/Accounts/'+recordId+'/Contacts';
request.httpMethod = 'GET';
RestContext.request = request;
Account thisAccount = AccountManager.getAccount();
System.assert(thisAccount != null);
System.assertEquals('Test record', thisAccount.Name);
}
static Id createTestRecord(){
Account TestAcc = new Account(
Name='Test record');
insert TestAcc;
Contact TestCon= new Contact(
LastName='Test',
AccountId = TestAcc.id);
return TestAcc.Id;
}
}