[SalesForce] How to return contact and account in a single method

In Salesforce Trailhead there is one Challenge available. Please find the challenge description below

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.

Based on last condition how can I return account and contact from same method ?
I returned Account object alone. but it throws the following exception.

MyCode:

Account result =  [SELECT ID,Name FROM Account WHERE Id = :accId];
return result;

Exception :

There was an unexpected error in your org which is preventing this assessment check from completing: 
System.ListException: List index out of bounds: 0

Best Answer

You will return a Account with contacts in same list.

Your SOQL should have inner query for contacts linked with account .

Code :

Account acc = [select id ,name ,(select id ,Name from contacts) from Account ];

When you return acc.contacts will hold contact list as well