Skip to content

Instantly share code, notes, and snippets.

@oximenvn
Last active August 19, 2019 07:49
Show Gist options
  • Save oximenvn/0e75ca684acd981e2fe89d25f018d007 to your computer and use it in GitHub Desktop.
Save oximenvn/0e75ca684acd981e2fe89d25f018d007 to your computer and use it in GitHub Desktop.
custom apex rest api
@RestResource(urlMapping='/Teams/*')
global with sharing class MyRestResource {
@HttpGet
global static List<Team__c> getTeamById() {
RestRequest request = RestContext.request;
RestResponse res = RestContext.response;
// grab the caseId from the end of the URL
String teamId = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
List<Team__c> result = null;
if (teamId.length()>0){
// search by TeamId
result = [SELECT Name, LeaderId__c, CreatedById, LastModifiedById
FROM Team__c
WHERE Id = :teamId];
}else{
// select all
result = [SELECT Name, LeaderId__c, CreatedById, LastModifiedById
FROM Team__c];
}
return result;
}
@HttpPost
global static Team__c createTeam(String name, String LeaderId) {
if (name == null ){
throw new ApexException('Name is required.');
}
if (name.length()==0){
throw new ApexException('Name is required.');
}
Team__c newTeam = new Team__c();
newTeam.Name = name;
newTeam.LeaderId__c = LeaderId;
insert newTeam;
return newTeam;
}
@HttpPut
global static Team__c putTeam(String id, String name, String leaderId){
boolean isNullId = False;
boolean isNullName = False;
// check required
if (name == null ){
isNullName = True;
}else{
if (name.length()<=0) isNullName = True;
}
if (id ==null){
isNullId = True;
}else{
if (id.length()<=0) isNullId = True;
}
if (isNullId && isNullName){
throw new ApexException('Id or Name is required.');
}
Team__c newTeam = new Team__c(
Id = id,
Name = name,
LeaderId__c = leaderId
);
if (!isNullId){
// update or insert by TeamId
upsert newTeam;
}else{
//update or insert by name
upsert newTeam name;
}
return newTeam;
}
@HttpPatch
global static Team__c updateTeam(){
RestRequest req = Restcontext.request;
String id = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
if (id == null ){
throw new ApexException('Id is required.');
}
if (id.length()==0){
throw new ApexException('Id is required.');
}
Team__c thisTeam = [SELECT Id FROM Team__c WHERE Id = :id];
// Deserialize
Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(req.requestBody.tostring());
for(String field : params.keySet()){
thisTeam.put(field, params.get(field));
}
update thisTeam;
return thisTeam;
}
@HttpDelete
global static void deleteTeam() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String id = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Team__c team = [SELECT Id FROM Team__c WHERE Id = :id];
delete team;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment