Creating Connection Using WebAPI

If you are looking for sample code to create a connection record using WebAPI for Dynamics 365 CE, this post will help you. You can change the lookup entity based on your requirement.
  1. function CreateConnection() {  
  2.     //get opportunity id  
  3.     var opportunityid = Xrm.Page.data.entity.getId().substring(1, 37); //remove {}  
  4.    
  5.     //get owner of opportunity  
  6.     var ownerid = Xrm.Page.getAttribute("ownerid").getValue()[0].id;  
  7.     ownerid = ownerid.substring(1, 37); //remove {}  
  8.    
  9.     //get server url  
  10.     var serverURL = Xrm.Page.context.getClientUrl();  
  11.    
  12.     //prepare entity object  
  13.     var connection = {};  
  14.     //set record1id lookup with opportunity  
  15.     connection["[email protected]"] = "/opportunities(" + opportunityid + ")";  
  16.    
  17.     //set record2id lookup with opportunity owner  
  18.     connection["[email protected]"] = "/systemusers(" + ownerid + ")";  
  19.     //setup connection role  
  20.     connection["[email protected]"] = "/connectionroles(EA5B38CE-A5EE-4CA0-A339-3A51B7DA87FE)"//connection role  
  21.    
  22.     connection.effectiveend = new Date();  
  23.    
  24.     var req = new XMLHttpRequest();  
  25.     req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/connections"true);  
  26.     req.setRequestHeader("OData-MaxVersion""4.0");  
  27.     req.setRequestHeader("OData-Version""4.0");  
  28.     req.setRequestHeader("Accept""application/json");  
  29.     req.setRequestHeader("Content-Type""application/json; charset=utf-8");  
  30.     req.onreadystatechange = function () {  
  31.         if (this.readyState === 4) {  
  32.             req.onreadystatechange = null;  
  33.             if (this.status === 204) {  
  34.                 Xrm.Utility.alertDialog('Connection Created...');  
  35.             } else {  
  36.                 Xrm.Utility.alertDialog("Error while creating Connection"+this.statusText);  
  37.             }  
  38.         }  
  39.     };  
  40.     req.send(JSON.stringify(connection));  
  41. }  

I hope it will help someone !! 

Next Recommended Reading Create Barcode With Powerapps

HIMBAP
We are expert in Microsoft Power Platform.