[SalesForce] get the list of contacts associated with account

I'm trying to get list of contacts associated with an account using REST.

I've created Connected app using tutorial

https://developer.salesforce.co/page/Getting_Started_with_the_Force.com_REST_API

So I created simple method

private void getAssosiatedContacts(String instanceUrl, String accessToken, PrintWriter writer) {
    String serviceUrl = instanceUrl + "/services/data/v31.0/sobjects/";
    HttpClient httpClient = new HttpClient();
    GetMethod gm = new GetMethod(serviceUrl);

    gm.setRequestHeader("Authorization", "Bearer " + accessToken);
    NameValuePair[] params = new NameValuePair[1];
    params[0] = new NameValuePair("q", "SELECT Name, "
                                    + "(SELECT Name FROM Contacts) "
                                    + "FROM Account WHERE Name='Chuck Chuck'");
    gm.setQueryString(params);

    try {
        httpClient.executeMethod(gm);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String response = null;
    try {
        response = gm.getResponseBodyAsString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    writer.write("\n\nAssosiated contacts\n");
    writer.write(response);
}

But the result on the page looks like this enter image description here

Where I wrong?

Best Answer

To execute a SOQL query using the REST API you need to use the query resource, not the sObjects resource.

You should get the results you expect by changing this line:

String serviceUrl = instanceUrl + "/services/data/v31.0/sobjects/";

To:

String serviceUrl = instanceUrl + "/services/data/v31.0/query/";
Related Topic