Sunday, August 23, 2020

Apex REST Annotations In Salesforce

Below are the supported "Apex REST Annotations In Salesforce".

@RestResource(urlMapping='/yourUrl')
@HttpDelete
@HttpGet
@HttpPatch
@HttpPost
@HttpPut

@RestResource

The @RestResource annotation is used at the class level and enables us to expose an Apex class as a REST resource.

To use @RestResource annotation, an Apex class must be defined as global.

@HttpDelete

This deletes the specified resource.

@HttpGet

This returns the specified resource.

@HttpPatch

This updates the specified resource.

@HttpPost

This creates a new resource.

@HttpPut

This creates or updates the specified resource.

To use @HttpDelete, @HttpGet, @HttpPatch, @HttpPost, @HttpPut Apex method must be defined as global static.

Example:


@RestResource(urlMapping='/getAccountOnExternalIdtofetchsinglerecord/*')
   global with sharing class getAccounttoSingleRecord {
      @Httpget
      global static Account fetchAccount(){
        Account obj=new Account();
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        string accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        obj=[Select id , name from Account where id=:accId];
        return obj;
      }
   }

What is the difference between @HttpPatch & @HttpPut in Salesforce?

@HttpPatch

This updates the specified resource.
Replace the part of  resource with the request received.

@HttpPut

This creates or updates the specified resource.
Replace the entire resource with the request received.

Hope, you like the post "Apex REST Annotations In Salesforce".

3 comments:

  1. Informative and easy to understand. Thank you for posting this content.

    ReplyDelete
  2. Useful information ..keep posting .

    ReplyDelete
  3. Easy to understand... Thanks for the blog.

    ReplyDelete