Ranjana
Ranjana

Reputation: 85

400 - Bad request error on POSTing a new record in CRM database using Web API

I am using CRM Web API to perform CRUD operations.

Field List Image of all custom fields Wherever Disabled is set, it is for field security.

For POST request when I execute this request with below code, it throws Bad Request error. My code sample is as below:

URL https://BaseURL/api/data/v8.2/transactions

jsonData

{
    "transactionnumber":"123456789123",
    "transactionamount":"500",
    "transactiondate":"2018-01-26T03:00:00.000Z"
}

Code:

public Dictionary<string, string> ExecutePostRequest(string entityName, string jsonFormattedData)
{
     string requestURL = GenerateRequestURL(entityName);
     HttpContent content = new StringContent(jsonFormattedData, Encoding.UTF8, "application/json");
     return DoRequest(requestURL.ToString(), content, HttpMethod.Post);
}

DoRequest method //which actually executes http request

private Dictionary<string, string> DoRequest(string requestUrl, HttpContent content, HttpMethod httpMethod)
{
    Dictionary<string, string> returnValue;
    HttpResponseMessage responseMessage;
    returnValue = new Dictionary<string, string>();
    try
    {
        HttpClient httpClient = SetUpCRMConnection();
        HttpRequestMessage request;
        request = new HttpRequestMessage(httpMethod, requestUrl);
        switch (httpMethod.ToString())
        {
            case "PATCH":
            case "POST":
            case "PUT":
                request.Content = content;
                break;
            case "DELETE":
                break;
        }
        responseMessage = httpClient.SendAsync(request).Result;
        return GetFormattedResponse(responseMessage);
    }
    catch (UriFormatException ex)
    {
        logger.Error(ex.InnerException);
        returnValue.Add("ERROR", "Invalid URL generated: " + ex.InnerException.ToString());
        return returnValue;
    }
    catch(Exception ex)
    {
        logger.Error(resourceManager.GetString("CRM_ConnectionLost"),ex);
        returnValue.Add("ERROR", resourceManager.GetString("CRM_ConnectionLost"));
        return returnValue;
    }
}

Upvotes: 2

Views: 2585

Answers (1)

Validate your entity name & attribute schema names, looks like they are custom but missing publisher prefix, ex. new_

Also datetime field should have .000 before Z.

"transactiondate":"2018-01-26T03:00:00.000Z"

Update:

String & Datetime datatypes should be enclosed in quotes.

Int, Decimal, Currency (Money) datatypes should not be enclosed in quotes. Try this:

"transactionamount":500

Upvotes: 2

Related Questions