Manage UserTerritory table through REST API

UserTerritory is one of the few objects that don’t allow DML Operations. However, we can manage it through the REST API.

We could assign a User to a Territory by using the following APEX code:

HttpRequest req = new HttpRequest();
Http http = new Http();

String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();

req.setEndpoint( baseUrl + '/services/data/v34.0/sobjects/UserTerritory/');
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId() );
req.setHeader('Content-type', 'application/json');
req.setMethod('POST');
// you need the UserId and TerritoryId beforehand and replace it in this body
req.setBody('{"UserId" : "","TerritoryId" : ""}');
try {
HttpResponse response = http.send(req);

if ( response.getStatusCode() != 200 ) {
System.debug('User assigned to the territory succesfully: ' + response.getBody());
} else {
System.debug('Error assigning the user to the territory: ' + response.getBody());
}

}
catch( exception ex){
system.debug('ex.getMessage());
}

If you want to remove a user from a territory, then the APEX code would looks like the following:

HttpRequest req = new HttpRequest();
Http http = new Http();

String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();

// you need the UserTerritory record Id and replace it in the URL
req.setEndpoint( baseUrl + '/services/data/v34.0/sobjects/UserTerritory/');
req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId() );
req.setMethod('DELETE');
try {
HttpResponse response = http.send(req);

if ( response.getStatusCode() != 200 ) {
System.debug('User removed from the territory succesfully: ' + response.getBody());
} else {
System.debug('Error removing the user from the territory: ' + response.getBody());
}

}
catch( exception ex){
system.debug(ex.getMessage());
}

Happy coding!

Leave a Reply

avatar
  Subscribe  
Notify of