In my previous post, I showed how to use the GlideRecord_Mutation API to update records in ServiceNow via a front-end widget. In this post, we'll expand on that by demonstrating how to insert new records and delete existing ones using the same out-of-the-box (OOTB) GraphQL API.
Inserting a Record with GlideRecord_Mutation
Just like updating a record, inserting a new record is straightforward with the GlideRecord_Mutation API. You define the necessary fields in the mutation, and ServiceNow handles the record creation.
Example GraphQL Mutation for Insert:
mutation ($short_description: String!, $priority: String) {
GlideRecord_Mutation {
insert_sn_hr_core_case(short_description: $short_description, priority: $priority) {
_row_data {
uniqueValue
displayValue
__typename
}
short_description {
value
}
priority {
value
}
}
}
}
Variables:
{
"short_description": "New HR Case Created",
"priority": "3"
}
Explanation:
Deleting a Record with GlideRecord_Mutation
Deleting records is just as simple. You'll provide the sys_id of the record to be deleted, and the mutation will handle the deletion process.
Example GraphQL Mutation for Delete:
mutation ($sys_id: String!) {
GlideRecord_Mutation {
delete_sn_hr_core_case(sys_id: $sys_id) {
_row_data {
uniqueValue
displayValue
__typename
}
}
}
}
Variables
{
"sys_id": "45ae83320b30220097432da0d5673a76"
}
Explanation:
You can perform both insert and delete operations from a Service Portal widget, similar to how you perform update operations. Here’s an example of using $http in an AngularJS widget for inserting a record:
function($scope, $http) {
var mutationQuery = `
mutation ($short_description: String!, $priority: String) {
GlideRecord_Mutation {
insert_sn_hr_core_case(short_description: $short_description, priority: $priority) {
_row_data {
uniqueValue
displayValue
__typename
}
short_description {
value
}
priority {
value
}
}
}
}
`;
var variables = {
short_description: 'New HR Case Created',
priority: '3'
};
var request = {
method: 'POST',
url: '/api/now/graphql',
headers: {
'Content-Type': 'application/json'
},
data: {
query: mutationQuery,
variables: variables
}
};
$http(request).then(function(response) {
console.log('Insert successful:', response.data);
}, function(error) {
console.error('Insert failed:', error);
});
}
The GlideRecord_Mutation API provides an efficient and flexible way to perform insert and delete operations, in addition to updates, all from the client-side in ServiceNow. By leveraging GraphQL, developers can manage records in a Service Portal or custom interfaces without writing server-side code, streamlining the development process.