Updating Data with Dynamics Web Api

When working with data via the Dynamics Web API, at some point you are going to want to update your data.

To accomplish this you will need to construct your entity in the same way you did for the insert only now you will use the Patch verb in submitting data to Dynamics.

My original entity code (the data I am updating) will look something like this.

JObject recordToUpdate = new JObject();
string entityFormat = “contacts(” + ContactId.AsQueryId() + “)”;
recordToUpdate[“my_customfield”] = “Some Data”;

Notes:

  • You must use the plural of the entity that you are submitting to the service (in this case contacts).
  • The Guid that you submit, cannot have the curly braces on either side.  For me, I created an Extension method that clears this out relatively easily.  This is the record we are looking to update in Dynamics.
  • Any fields you want to update, simply get their name and submit their data.

When you are ready to update your record, the code to do so is as follows;

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, Token);
httpClient.DefaultRequestHeaders.Add(“OData-MaxVersion”, “4.0”);
httpClient.DefaultRequestHeaders.Add(“OData-Version”, “4.0”);
httpClient.DefaultRequestHeaders.Add(“Prefer”, “odata.include-annotations=*”);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
httpClient.BaseAddress = new Uri(DynamicsTenantUrl + “/api/data/v9.1/”);

HttpRequestMessage updateRequest = new HttpRequestMessage(HttpMethod.Patch, entityFormat)
{
Content = new StringContent(recordToUpdate.ToString(), Encoding.UTF8, “application/json”)
};

HttpResponseMessage updateResponse = await httpClient.SendAsync(updateRequest);

Notes:

  • Upon submission, make sure you check the StatusCode of the updateResponse object to ensure things went smoothly.
  • You must have a valid token (i.e., have already connected to Dynamics before having executed this query).
  • The entityFormat variable is passed into the Original HTTP Request and the recordToUpdate variable is passed in as part of the content

When executed, you should see your information being updated back to Dynamics (assuming of course that your application has permissions to do this).

Post A Reply

%d bloggers like this: