- We need to know the ID of the company we are going to create the data for. If you have completed the previous recipe (Business Central API – retrieving data), then you may already have this information.
If you do not have this information, then download the ch7/5-api-retrieving-data/scripts/1-GetCompanies.ps1 script from the GitHub and run it. Note the ID of the company you want to create the data for.
- Open PowerShell ISE.
- Create a new script and add the following code:
$username = '<replace with your userName>'
$webServicesKey = '<replace with your web services key'
$azureDomain = '<replace with your Azure domain>'
$companyId = '<replace with the company id from Step 1>'
Make sure to update the previous code with your specific information from your development sandbox.
- Now, add the following code to create the credentials we need to pass with the web request:
$credentials = "$($username):$($webServicesKey)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credentials))
$headers = @{ Authorization = "Basic $encodedCredentials" }
- We're going to create a simple item record. Add the code that will populate a few of the fields and make the request:
$url = 'https://api.businesscentral.dynamics.com/v1.0/' + $azureDomain + '/sandbox/api/v1.0/companies(' + $companyId + ')/items'
$params = @{"displayName"="My Api item";
"itemCategoryCode"="MISC";
"type"="Inventory";
}
Invoke-RestMethod -Uri $url -Method POST -Headers $headers -Body ($params|ConvertTo-Json) -ContentType "application/json"
Save the script as 1-CreateItem.ps1.
- Now, run the script. If all goes well, then your item will be created and you should see a response similar to the following screenshot:
Note the number. You can look up that item through your web browser in your sandbox in order to verify that it has, in fact, been created.