I have a requirement to fetch query results of a SOQL query using REST API. Even after encoding the SOQL search I keep on getting Malformed Query error. I am so far unable to find a reason to it.

This is how I am constructing the endpoint :

    String sfdcEndPoint = "https://something--env.my.salesforce.com/services/data/v51.0/query/?q=";
    String Query = "select Id, Object__r.Contract_Terms__c,Object2__r.Free_Month_Period__c,Object3__r.CurrentContractStartDate__c, EndDate__c, Object4__r.Free_Month_End_Date__c, Object5__r.name, ProductId__r.ProductType__c, ProductId__r.Is_3rd_Party__c, Is_EPP__c, Charge_Frequency__c, PriceType__c, Perpetual__c, NetUnitPrice__c, billing_tcv__c, Billing_MRR__c from OrderLineItem__c where OrderId__c IN('"+orderId+"')order by ProductId__r.ProductType__c, Charge_Frequency__c";

    String sfdcQuery= sfdcEndPoint+URLEncoder.encode(Query, StandardCharsets.UTF_8);

This is the query formed post encoding


I ran the query in dev console as well as workbench where I am seeing the proper result but not sure why I cannot get one using Rest API.

So far I have tried replacing "query" with "search" in endpoint. Tried to simply the query by removing cross object references but i continue getting 400 as response. Ran with both encoded and non encoded URL.

Response :

{"message":"A query string has to be specified","errorCode":"MALFORMED_QUERY"}

Please feel free to guide me to a existing question/documentation that might help me in resolving this issue.

1 Answer 1


The issue might be here OrderId__c IN('"+orderId+"')order here you need to give space between ) and order i.e OrderId__c IN('"+orderId+"') order If the issue still persisted make sure that orderId values are comma-separated(If multiple values)

While encoding query use this format : /services/data/v52.0/query/?q=SELECT+name+from+Account you don't need to urlencode it.

  • Thanks Aniket, I updated this and still no luck. Also orderId will be having only single value. I replaced = with IN to check if it has something to do with this issue. Commented Apr 30, 2021 at 9:00
  • Hi Kovid, There is an issue with your query encoding. you have to write custom encoding logic for API query string. Refer to this document developer.salesforce.com/docs/atlas.en-us.232.0.api_rest.meta/…
    – Aniket
    Commented May 5, 2021 at 13:28

You must log in to answer this question.

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