WebApi
The Hsl.WebAPI namespace provides methods for accessing the Web API web services endpoint. The 'main' class in this namespace is the client class. You can access the client class using Hsl.WebApi.getClient(VERSION)
.
⚠️ Methods in Hsl.WebApi will not work in the App for Outlook. Use Xrm.WebApi methods instead.
function createAccountWithName(name) {
const client = Hsl.WebApi.getClient('9.1');
return client.create('account', {
name: name,
});
}
getClient
Hsl.WebApi.getClient(version: string): Hsl.WebApi.Client
Hsl.WebApi.getClient(cfg: ServiceConfig): Hsl.WebApi.Client
interface ServiceConfig {
/* If true, calling record.getValue for an unknown property on a WebApiRecord will return null instead of throw an exception */
allowUnknownGet?: boolean;
/* The version of the webapi endpoint to use */
apiVersion?: string;
/* The root url for the webapi endpoint */
rootUrl?: string;
/* The caller id for impersonated web service calls.
* See https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/webapi/impersonate-another-user-web-api */
callerId?: string;
/* The Xrm.GlobalContext (return value from Xrm.Utility.getGlobalContext()) */
context?: Xrm.GlobalContext;
/** Whether to automatically wait/retry if [Service Protection Limits](https://docs.microsoft.com/en-us/power-apps/developer/data-platform/api-limits) are hit.
* This can be overridden for an individual request using the autoRetryServiceProtectionErrors setting for that request. */
autoRetryServiceProtectionErrors?: boolean;
/** Callback made when a service protection error is hit.
* NOTE: this could be called multiple times for the same request.
* This setting only works when autoRetryServiceProtectionErrors is set to true. */
onServiceProtectionError?: (this: void, ctx: OnServiceProtectionErrorContext) => void;
}
async function test() {
let client = Hsl.WebApi.getClient({
autoRetryServiceProtectionErrors: true,
apiVersion: '9.2',
});
const result = await client.create('account', {
name: 'My Test Account',
});
}
See: Client
Returns a webapi client for the specified version.
encodeDateOnly
Hsl.WebApi.encodeDateOnly(date: Date | Moment | luxon.DateTime): string;
Hsl.WebApi.encodeDateOnly(date: null): null;
Encodes the specified date in the format used by attributes with data only behavior for the WebApi endpoint.
function createDateOnlySample() {
return Hsl.WebApi.getClient('9.0').create('hsl_entityname', {
hsl_dateonly: Hsl.WebApi.encodeDateOnly(new Date()),
hsl_dateonly2: Hsl.WebApi.encodeDateOnly(luxon.DateTime.now()),
hsl_dateonly3: Hsl.WebApi.encodeDateOnly(luxon.DateTime.utc(2021, 3, 8)),
});
}
encodeTziDateTime
Hsl.WebApi.encodeTziDateTime(date: Date | Moment | luxon.DateTime): string;
Hsl.WebApi.encodeTziDateTime(date: null): null;
Encodes the specified date in the format used by attributes with time zone independent behavior for the WebApi endpoint.
function createDateTimeTziSample() {
return Hsl.WebApi.getClient('9.0').create('hsl_entityname', {
hsl_timezoneindependent: Hsl.WebApi.encodeTziDateTime(new Date()),
hsl_timezoneindependent2: Hsl.WebApi.encodeTziDateTime(luxon.DateTime.utc(2020, 5, 3, 7, 30)),
hsl_timezoneindependent3: Hsl.WebApi.encodeTziDateTime(luxon.DateTime.local(2020, 5, 3, 16, 30)),
});
}
encodeGuid [Deprecated]
⚠️ This method is no longer necessary with the latest version of the webapi endpoint. WebApi no longer errors if a guid is surrounded by curly brackets like it did in older versions.
Hsl.WebApi.encodeGuid(guid: string): string;
Encodes a guid for use with a WebApi query filter. This method is needed if the guid may have curly brackets on it. If you know your guid won't have curly brackets, calling this method is unnecessary but won't harm things.
function getOpportunitiesByAccountId(accountId) {
return Hsl.WebApi.getClient('9.0').query('opportunity', {
select: ['name', 'estimatedvalue'],
filter: `_parentaccountid_value eq ${accountId}`,
}).then(console.log).catch(console.error);
}
bindReference
Hsl.WebApi.bindReference(recordReference: null | undefined | WebApiReference): any;
Hsl.WebApi.bindReference(entityName: string, id: string|null|undefined): any;
For example, you might find
<NavigationProperty Name="hsl_AccountId" Type="mscrm.account" Nullable="false" Partner="hsl_account_hsl_sample">
function createAccountWithPrimaryContactSample() {
return Hsl.WebApi.client.create('account', {
name: 'Create Account',
primarycontactid: Hsl.WebApi.bindReference('contact', 'cb642c30-47df-4846-815b-02f763fcd302'),
});
}
function updateCustomFieldSample() {
return Hsl.WebApi.client.update({ entityType: 'hsl_sample', id: 'D9F25334-DA16-4A8C-BC53-F8D1507DFB5D' }, {
hsl_AccountId: Hsl.WebApi.bindReference('account', 'DA05E781-65C3-4499-B0B5-DD4B30A4ADD5'),
});
}
function bindReferenceActionSample() {
const client = Hsl.WebApi.getClient('9.0');
return client.action({
name: 'CloseIncident',
parameters: {
IncidentResolution: Hsl.WebApi.encodeEntityType('incidentresolution', null, {
subject: 'Resolve Case',
incidentid: Hsl.WebApi.bindReference({
entityType: 'incident',
id: '{3B68BC21-B7BF-418F-8CD8-1525A6E8533C}',
}),
}),
Status: 5,
}
});
}
encodeString
Hsl.WebApi.encodeString(value: string): string;
Encodes a string for use in Web API filters.
function findJohnsWithLastNameSample(lastname) {
const client = Hsl.WebApi.getClient('9.0');
return client.query('contact', {
// Put single quotes around the name to encode it.
// This will allow us to handle last names with apostrophes in them like "O'Neil".
filter: `firstname eq 'John' and lastname eq ${Hsl.WebApi.encodeString(lastname)}`,
select: ['fullname', 'telephone1']
});
}
encodeEntityType
Hsl.WebApi.encodeEntityType(entityName: string, id: string|null, additionalFields: any): unknown;
Hsl.WebApi.encodeEntityType(recordReference: PrimaryIdReference, additionalFields: any): unknown;
Encodes parameter for use with some actions that use a crmbaseentity parameter or a class that extends crmbaseentity. Use additionalFields when encoding any entityType that takes additional field data like CloseIncident's IncidentResolution parameter.
function entityTypeActionExample() {
const client = Hsl.WebApi.getClient('9.0');
// See https://docs.microsoft.com/en-us/dynamics365/customer-engagement/web-api/routeto?view=dynamics-ce-odata-9
// for parameter details.
return client.action({
name: 'RouteTo',
parameters: {
Target: Hsl.WebApi.encodeEntityType('systemuser', '033EF541-DBAF-4E0D-A306-A8BD9A062337'),
QueueItem: Hsl.WebApi.encodeEntityType({
entityType: 'queueitem',
id: 'b5f3049c-46d7-45e0-b80b-b2e73ac059bc',
}),
}
});
}
function entityTypeWithFieldsResolveCaseExample() {
const client = Hsl.WebApi.getClient('9.0');
return client.action({
name: 'CloseIncident',
parameters: {
IncidentResolution: Hsl.WebApi.encodeEntityType('incidentresolution', null, {
subject: 'Resolve Case',
incidentid: Hsl.WebApi.bindReference({
entityType: 'incident',
id: '{3B68BC21-B7BF-418F-8CD8-1525A6E8533C}',
}),
}),
Status: 5,
}
});
}
getValuePropertyName
Hsl.WebApi.getValuePropertyName(attrName: string): string;
WebApi uses _ATTRIBUTENAME_value for the keys of lookup properties. This function takes the attribute name as input and returns the Web API value property.
function queryBasedOnOpportunityLookupValue(context) {
const client = Hsl.WebApi.getClient('9.0');
// Find opportunties based on the transaction currency.
return client.query('opportunity', {
select: ['name', 'estimatedvalue'],
filter: `${Hsl.WebApi.getValuePropertyName('transactioncurrencyid')} eq {EF8379E0-B9A8-E511-80BD-0800278A357E}`,
});
}
parseDateOnly
Hsl.WebApi.parseDateOnly(value: string): Date;
Hsl.WebApi.parseDateOnly(value: null): null;
Parses the value of a date only field value returned from the webapi endpoint into a javascript Date object.
function parseDateTimesSample() {
return Hsl.WebApi.getClient('9.0').retrieve({
entityType: 'hsl_sample',
id: '0A198417-B06F-413B-8CFC-B654C916A964',
}, ['hsl_dateonly', 'hsl_datetimetzi', 'hsl_userlocaldatetime']).then(record => {
const dateOnly = Hsl.WebApi.parseDateOnly(record.hsl_dateonly);
const dateTimeTzi = Hsl.WebApi.parseTziDateTime(record.hsl_datetimetzi);
const dateTimeUserLocal = new Date(record.hsl_userlocaldatetime);
// NOTE: moment is NOT included as part of the library. These methods will fail
// unless moment is loaded on the page. https://momentjs.com/
const momentDateOnly = moment(record.hsl_dateonly);
const momentTzi = Hsl.WebApi.parseTziMoment(record.hsl_datetimetzi);
const momentUserLocal = moment(record.hsl_userlocaldatetime);
// NOTE: luxon is NOT included as part of the library. These methods will fail
// unless luxon is loaded on the page. https://moment.github.io/luxon/
const luxonDateOnly = luxon.DateTime.fromISO('2020-03-04');
const luxonDateOnlyUtc = luxon.DateTime.fromISO('2020-03-04', { zone: 'UTC' });
const luxonTzi = luxon.DateTime.fromISO('2020-05-08T00:15:03Z');
const luxonTziUtc = luxon.DateTime.fromISO('2020-05-08T00:15:03Z', { zone: 'UTC' });
const luxonUserLocal = luxon.DateTime.fromISO('2020-05-08T00:15:03Z');
const luxonUserLocalUtc = luxon.DateTime.fromISO('2020-05-08T00:15:03Z', { zone: 'UTC' });
});
}
parseTziDateTime
Hsl.WebApi.parseTziDateTime(value: string): Date;
Hsl.WebApi.parseTziDateTime(value: null): null;
Parses the value of a time zone independent field value returned from the webapi endpoint into a javascript Date object.
function parseDateTimesSample() {
return Hsl.WebApi.getClient('9.0').retrieve({
entityType: 'hsl_sample',
id: '0A198417-B06F-413B-8CFC-B654C916A964',
}, ['hsl_dateonly', 'hsl_datetimetzi', 'hsl_userlocaldatetime']).then(record => {
const dateOnly = Hsl.WebApi.parseDateOnly(record.hsl_dateonly);
const dateTimeTzi = Hsl.WebApi.parseTziDateTime(record.hsl_datetimetzi);
const dateTimeUserLocal = new Date(record.hsl_userlocaldatetime);
// NOTE: moment is NOT included as part of the library. These methods will fail
// unless moment is loaded on the page. https://momentjs.com/
const momentDateOnly = moment(record.hsl_dateonly);
const momentTzi = Hsl.WebApi.parseTziMoment(record.hsl_datetimetzi);
const momentUserLocal = moment(record.hsl_userlocaldatetime);
// NOTE: luxon is NOT included as part of the library. These methods will fail
// unless luxon is loaded on the page. https://moment.github.io/luxon/
const luxonDateOnly = luxon.DateTime.fromISO('2020-03-04');
const luxonDateOnlyUtc = luxon.DateTime.fromISO('2020-03-04', { zone: 'UTC' });
const luxonTzi = luxon.DateTime.fromISO('2020-05-08T00:15:03Z');
const luxonTziUtc = luxon.DateTime.fromISO('2020-05-08T00:15:03Z', { zone: 'UTC' });
const luxonUserLocal = luxon.DateTime.fromISO('2020-05-08T00:15:03Z');
const luxonUserLocalUtc = luxon.DateTime.fromISO('2020-05-08T00:15:03Z', { zone: 'UTC' });
});
}
encodeFunction
Hsl.WebApi.encodeFunction(functionName: string, parameters: Dictionary<any>): string;
Encodes a function for use in a webapi query filter. Functions in the Microsoft.Dynamics.CRM namespace can be shortened by prefixing the function name with a single period. For example ".Above" is a shortcut for "Microsoft.Dynamics.CRM.Above". The following parameter types passed to encodeFunction should be encoded themselves:
- date – usually encoded with encodeDateOnly but might differ depending on the function being called.
See these documentation pages for additional details.
function encodeFunctionSample() {
return Hsl.WebApi.getClient('9.0').queryAll('account', {
select: 'name',
filter: Hsl.WebApi.encodeFunction('.OnOrAfter', {
PropertyName: 'createdon',
PropertyValue: Hsl.WebApi.encodeDateOnly(new Date(2020, 5, 3)),
}),
});
}
function inFilterFunction() {
const client = Hsl.WebApi.getClient('9.0');
// https://msdn.microsoft.com/en-us/library/mt607541.aspx
// Because of how In is defined, the values are always strings regardless of the property type.
client.query('account', {
select: 'name',
filter: Hsl.WebApi.encodeFunction('.In', {
PropertyName: 'industrycode',
PropertyValues: ['5', '8'],
}),
});
}
function underFilterFunction(accountId) {
const client = Hsl.WebApi.getClient('9.0');
// Queries all child accounts under the given accountid
return client.query('account', {
select: 'name',
filter: Hsl.WebApi.encodeFunction('.Under', {
PropertyName: 'accountid',
PropertyValue: accountId,
}),
});
}
function startsWithFilter() {
const client = Hsl.WebApi.getClient('9.0');
// For startswith/contains/endswith, just reference the function directly.
return client.query('account', {
select: ['accountid'],
filter: `contains(name, ${Hsl.WebApi.encodeString("O'Neil")})`,
});
}