Solution: “Bad Request” error in Dynamics 365 Web API

CRM


If you have faced an error of "Bad Request" while using Dynamics 365 web API, then here we as a Microsoft Dynamics CRM Services discussed step by step solutions with all the required code. 

 

I know this blog is very simple but can be cause major issue if you are not following. Sometime we may have a requirement to retrieve some entity record using some filter condition with some field value which enters by users.

 

For example, I am trying to retrieve accounts with a filter condition. Here I have passed parameter field value “new_corporatename” which provided by users.  

 

        var Name = Xrm.Page.getAttribute("new_corporatename").getValue();    

        var req = new XMLHttpRequest();

         var globalContext = Xrm.Utility.getGlobalContext();   

        req.open("GET"globalContext.getClientUrl() "/api/data/v9.0/accounts?$select=accountid,name&$filter=name eq '" +  Name + "'"true); 

        req.setRequestHeader("OData-MaxVersion""4.0"); 

        req.setRequestHeader("OData-Version""4.0"); 

        req.setRequestHeader("Accept""application/json"); 

        req.setRequestHeader("Content-Type""application/json; charset=utf-8"); 

        req.setRequestHeader("Prefer""odata.include-annotations=\"*\""); 

        req.onreadystatechange = function () { 

            if (this.readyState === 4) { 

                req.onreadystatechange = null; 

                if (this.status === 200) { 

                    var results = JSON.parse(this.response); 

                    if (results.value.length > 0) { 

                        hasAccount = true; 

                    } 

                 } else { 

                    hasAccount = false;                     

                } 

            } 

        }; 

        req.send(); 

 

If you see in below line, we may provide any value in the input text field “new_corporatename”. By any chance if you put any special character like “&”, you will get an error “Bad Request”. 

 

req.open("GET"Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts?$select=accountid,name&$filter=name eq '" +  Name + "'"true); 

 

To avoid such kind of error you always need to encode the value while writing query like below. 

 

req.open("GET"Xrm.Page.context.getClientUrl() + "/api/data/v8.1/accounts?$select=accountid,name&$filter=name eq '" + encodeURIComponent(Name) + "'"true); 


In summary always encode variable text while passing parameter in your web API URL using encodeURIComponent This is one of the best practices while writing web API. 


Click to Get Solution of an Error A currency is required if a value exists in a money field. Select a currency and try again