Custom Salesforce HTTPPost API
We have had the concept of an API for a while now. It is something that helps us connect two various types of systems with the help of data exchange. Salesforce also has a rest API of its own and it is very handy for a lot of tasks. However, it is not where the awesomeness of this platform see limits. Salesforce also provides us with the option to create our own post API. How can we do it? Let me show you an example of creating a custom salesforce HTTPPost API.
APEX Code
Creating an API will be an easy task for seasoned developers who have worked in APEX. The code for a simple APEX class is as follows.
@RestResource (urlmapping = '/newaccount/*') global class PostAccountAndContact { @HttpPost global static void saveAccountAndContact(string accountName, string contactFirst, string contactLast){ account acc = new account(name = accountName); RestContext.response.addHeader('Content-Type', 'application/json'); savepoint sp = database.setSavepoint(); if(accountName != null && accountName != ''){ insert acc; contact con = new contact(lastName = contactLast,firstName = contactFirst, accountid = acc.id); if(contactLast != null && contactLast != ''){ insert con; RestContext.response.responseBody = Blob.valueOf('{"AccountId":"'+acc.id+'", "ContactId":"'+con.id+'"}'); }else{ database.rollback(sp); RestContext.response.responseBody = Blob.valueOf('{"error":"Contact Last Name cannot be null"}'); } }else{ RestContext.response.responseBody = Blob.valueOf('{"error":"Account Name cannot be null"}'); } } }
In the above code, we are creating an account with a contact and linking the contact to account. For this, we have provided three different variables out of which one is for account name and two are for contact first and last name. First, we have created the class with the annotation @RestResource. It marks the class as containing some rest API methods. The function which we want to make as the post method is annotated as @HttpPost. This way we can create a post method in our class. In the end, we have used a RestContext class which is setting the responseBody of the API. Once this is done our API’s POST method is prepared.
Testing the API
This next part is simple. In order to test the working of the API go to https://workbench.developerforce.com/. Login and then navigate to Utilities|RestExplorer. Here type the following URL:
/services/apexrest/<org_namespace>/newaccount/
If the org does not have a namespace then simply skip the ‘<org_namespace>/’ part.
Select the method as POST and set the body for the request.
{"accountName":"Webkul","contactFirst":"John","contactLast":"Doe"}
Once this is done click on the execute button, and then see the newly created account in the Org.
Support
That’s all about Custom salesforce HTTPPost API, for any further queries feel free to contact us at:
https://wedgecommerce.com/contact-us/
Or let us know your views about this blog in the comments section below.