In this tutorial we will learn how to perform CRUD operations using Dynamics CRM 2016 Web API.The CRUD operations (create, retrieve, update and delete) are explained separately along with the Request and Response messages.
Create
Use a POST request to send data to create an entity. To create a new entity you must identify the valid property names and types.
Request
POST [organization URI]/api/data/v8.0/accounts HTTP/1.1 Content-Type: application/json; charset=utf-8 OData-MaxVersion: 4.0 OData-Version: 4.0 Accept: application/json { "name": "Sample Account", "creditonhold": false, "address1_latitude": 47.639583, "description": "This is the description of the sample account", "revenue": 5000000, "accountcategorycode": 1 }
Response
HTTP/1.1 204 No Content OData-Version: 4.0 OData-EntityId: [organization URI]/api/data/v8.0/accounts(7eb682f1-ca75-e511-80d4-00155d2a68d1)
Code
To create entity record, you can use the following code.
function createOperationUsingWebAPI() { var clientUrl = Xrm.Page.context.getClientUrl(); var req = new XMLHttpRequest() req.open("POST", encodeURI(clientUrl + "/api/data/v8.0/accounts"), true); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.onreadystatechange = function () { var accountUri = this.getResponseHeader("OData-EntityId"); }; var body = JSON.stringify({ "name": "Sample Account", "creditonhold": false, "address1_latitude": 47.639583, "description": "This is the description of the sample account", "revenue": 5000000, "accountcategorycode": 1 }); req.send(body); }
The response OData-EntityId header contains the Uri of the created entity.
Image may be NSFW.
Clik here to view.
Create related entities in one operation
You can create entities related to each other by defining them as navigation properties values.
For example, the following request body posted to the Account entity set will create a total of four new entities in the context of creating an account.
- A contact is created because it is defined as an object property of the single-valued navigation property primarycontactid.
- An opportunity is created because it is defined as an object within an array that is set to the value of a collection-valued navigation property opportunity_customer_accounts.
- A task is created because it is defined an object within an array that is set to the value of a collection-valued navigation property Opportunity_Tasks
Request
POST [organization URI]/api/data/v8.0/accounts HTTP/1.1 Content-Type: application/json; charset=utf-8 OData-MaxVersion: 4.0 OData-Version: 4.0 Accept: application/json { "name": "Sample Account", "primarycontactid": { "firstname": "John", "lastname": "Smith" }, "opportunity_customer_accounts": [ { "name": "Opportunity associated to Sample Account", "Opportunity_Tasks": [ { "subject": "Task associated to opportunity" } ] } ] }
Response
HTTP/1.1 204 No Content OData-Version: 4.0 OData-EntityId: [organization URI]/api/data/v8.0/accounts(3c6e4b5f-86f6-e411-80dd-00155d2a68cb)
Associate entities on create
To associate new entities to existing entities i.e. set the value of lookup field, when they are created you must set the value of single-valued navigation properties using the @odata.bind annotation.
Request
POST [organization URI]/api/data/v8.0/accounts HTTP/1.1 Content-Type: application/json; charset=utf-8 OData-MaxVersion: 4.0 OData-Version: 4.0 Accept: application/json { "name":"Sample Account", "primarycontactid@odata.bind":"/contacts(00000000-0000-0000-0000-000000000001)" }
Response
HTTP/1.1 204 No Content OData-Version: 4.0 OData-EntityId: [organization URI]/api/data/v8.0/accounts(00000000-0000-0000-0000-000000000002)
Retrieve
Use a GET request to retrieve data for an entity specified as the resource with a unique identifier. When retrieving an entity you can also request specific properties and expand navigation properties to return properties from related entities.
Request
GET [Organization URI]/api/data/v8.0/</span>accounts?$select=name&$top=3 Accept: application/json Content-Type: application/json; charset=utf-8 OData-MaxVersion: 4.0 OData-Version: 4.0
Response
The response of the above request will retrieve the top 3 accounts.
{"@odata.context":"[Organization URI]/api/data/v8.0/$metadata#accounts(name)", "value":[ {"@odata.etag":"W/\"604548\"","name":"Updated Sample Account ", "accountid":"ce49991c-c3b5-e511-80de-6c3be5a8ad10" }, {"@odata.etag":"W/\"604439\"","name":"Alice Watson","accountid":"dfa66bf0-c4b5-e511-80d9-6c3be5a8c0c4"}, {"@odata.etag":"W/\"604432\"","name":"Fourth Coffee (sample)","accountid":"f3c02416-d9aa-e511-80d9-f0921c194360" } ]}
Code
function retrieveOperationUsingWebAPI() { var clientUrl = Xrm.Page.context.getClientUrl(); var req = new XMLHttpRequest(); req.open("GET", encodeURI(clientUrl + "/api/data/v8.0/accounts?$select=name&$top=3"), true); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.onreadystatechange = function () { if (this.readyState == 4 /* complete */) { req.onreadystatechange = null; if (this.status == 200) { } else { var error = JSON.parse(this.response).error; } } }; req.send(); }
Retrieve using alternate key
If an entity has an alternate key defined, you can also use the alternate key to retrieve the entity instead of the unique identifier for the entity. For example, if the Contact entity has an alternate key definition that includes both the firstname and emailaddress1 properties, you can retrieve the contact using a query with data provided for those keys as shown here.
Any time you need to uniquely identify an entity to retrieve, update, or delete, you can use alternate keys configured for the entity. By default, there are no alternate keys configured for entities. Alternate keys will only be available if the organization adds them.
GET [Organization URI]/api/data/v8.0/contacts(firstname=’Joe’,emailaddress1=’abc@example.com’)
Update
For Update operation, we use the HTTP PATCH verb. Pass a JSON object containing the properties you want to update to the URI that represents the entity. When updating an entity, only include the properties you are changing in the request body. Simply updating the properties of an entity that you previously retrieved, and including that JSON in your request, will update each property even though the value is the same
Request
PATCH [organization URI]/api/data/v8.0/accounts(00000000-0000-0000-0000-000000000001) HTTP/1.1 Content-Type: application/json OData-MaxVersion: 4.0 OData-Version: 4.0 { "name": "Updated Sample Account ", "creditonhold": true, "address1_latitude": 47.639583, "description": "This is the updated description of the sample account", "revenue": 6000000, "accountcategorycode": 2}
Response
A response with a status of 204 will be returned if the update is successful.
HTTP/1.1 204 No Content OData-Version: 4.0
Code
To update an entity record, use the following code
function updateOperationUsingWebAPI() { var clientUrl = Xrm.Page.context.getClientUrl(); var req = new XMLHttpRequest(); req.open("PATCH", encodeURI(clientUrl + "/api/data/v8.0/accounts(CE49991C-C3B5-E511-80DE-6C3BE5A8AD10)"), true); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); var body = JSON.stringify({ "name": "Updated Sample Account ", "creditonhold": true, "address1_latitude": 47.639583, "description": "This is the updated description of the sample account", "revenue": 6000000, "accountcategorycode": 2 }); req.send(body); }
Update a single property value
If you want to update a single property then use the HTTP PUT verb. And append the property name with the Url
Request
PUT [organization URI]/api/data/v8.0/accounts(00000000-0000-0000-0000-000000000001)/name HTTP/1.1 Content-Type: application/json OData-MaxVersion: 4.0 OData-Version: 4.0 {"value": "Updated Sample Account Name"}
Response
HTTP/1.1 204 No Content OData-Version: 4.0
Delete
To delete a record, we use the DELETE verb with the url.
Request
DELETE [organization URI]/api/data/v8.0/accounts(00000000-0000-0000-0000-000000000001) HTTP/1.1 Content-Type: application/json OData-MaxVersion: 4.0 OData-Version: 4.0
Response
If the entity exists, you’ll get a normal response with status 204 to indicate the delete was successful. If the entity isn’t found, you’ll get a response with status 404.
HTTP/1.1 204 No Content OData-Version: 4.0
Code
Use the following code to delete a record
function deleteOperationUsingWebAPI() { var clientUrl = Xrm.Page.context.getClientUrl(); var req = new XMLHttpRequest(); req.open("DELETE", encodeURI(clientUrl + "/api/data/v8.0/accounts(A6CBCA4A-CAB5-E511-80DE-6C3BE5A8AD10)"), true); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.send(); }
In this way you can perform any CRUD operations using the Dynamics CRM 2016 Web API.