function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Radhe Shyam.Radhe Shyam. 

REST API get data from 3rd party and create opportunity in salesforce

Hi Team,
I am new to REST and integration and all. I have read about get post put patch delete and tried to do transaction on rest client.

But now i got requirement like:
I need to create oppty in salesforce from getting the data from 3rd party system.
Data will be in jSON format.

What will be the steps ...can anyone please guide me with sample code snippt.

Thanks You
Radhe S
Ajay K DubediAjay K Dubedi
Hi,
If you are getting jSon data from a website or 3rd party. you need to follow these steps:-
1.GOTO remote site settings and create a new remote setting and add the endpoint url.
2. There are several websites available that will create a wrapper class of your jSon data so you just need to use the data by making a few changes.
https://json2apex.herokuapp.com (https://json2apex.herokuapp.com/)
You can refer to the following code for an idea:-
public class JSON2Apex {
   
    public  static void parse() 
    {
          
        list<string> ctyList= new list<string>();
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://data.medicare.gov/resource/c8qv-268j.json');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        system.debug(':::::::::::::::::'+response.getBody());
        
       list<Object>  results =(list<Object>)JSON.deserializeuntyped(response.getBody());
        
       system.debug(':::::::::::::::::'+results);
        
    }
   
    public class JSON2Apex1 {
        
        public String adr_ln_1;
        public String adr_ln_2;
        public String assgn;
        public String cty;
        public String frst_nm;
        public String gndr;
        public String grd_yr;
        public String ind_enrl_id;
        public String ind_pac_id;
        public String lst_nm;
        public String med_sch;
        public String mid_nm;
        public String npi;
        public String phn_numbr;
        public String pri_spec;
        public String st;
        public String zip;
    }
}

User-added image
Thanks 
Ajay
Maharajan CMaharajan C
Hi Radhe,

-->The below sample for create the task in Salesforce using the REST API.Here you are going to consume the data from external system.

-->Then you have to create the global class like below and provide the endpoint url as  https://rajaccountgeolocationapp-dev-ed.my.salesforce.com/services/apexrest/demo/createTask/    to endsystem

-->please read the comments in the below codes which will give a very good idea to you

*/
//@RestResource annotation exposes the class as a REST resource
@RestResource(urlMapping='/demo/createTask/*') //endpoint definition to external system > {Salesforce Base URL}/services/apexrest/demo/createTask/
global class createTask {
    
    //primary logic for the class
    @HttpPost //HttpPost annotation exposes the method as a REST resource and called when an HTTP POST request is sent
    global static responseWrapper taskCreationLogic() {
        
        RestRequest req = RestContext.request; //the RestRequest for the Apex REST method
        responseWrapper responseJSON = new responseWrapper(); //responseWrapper object for API response
        
        String typeOfCard = ''; //placeholder for the type of card string
        String last4OfCard = ''; //placeholder for the last four digits of the card
        String emailAddress = ''; //placeholder for an email address
        Map<String, Object> body = new Map<String, Object>(); //placeholder for the JSON Body of the request
        Map<String, Object> src = new Map<String, Object>(); //placeholder for the source object from the JSON request
        
        String jsonBody = req.requestBody.toString(); //the body of the request
        
        if (!String.isBlank(jsonBody)) { //if the request body is NOT white space, empty ('') or null
            body = (Map<String, Object>)JSON.deserializeUntyped(jsonBody); //deserializes the JSON string into collections of primitive data types
            if (body.containsKey('description')) { //if there is a key of description in our body map
                emailAddress = (String)body.get('description'); //grab the value for the description key from the body map and cast it to a string
                List<Contact> queriedContacts = [SELECT Id FROM Contact WHERE Email = :emailAddress ORDER BY CreatedDate DESC LIMIT 1]; //query for a Contact that has the email address
                if (!queriedContacts.isEmpty()) { //if the list is not empty
                    if (body.containsKey('source')) { //if there is a key of source in our body map
                        src = (Map<String, Object>)body.get('source'); //grab the value for the source key from the body map and cast it to a new map (String > primative data types)
                        if (src.containsKey('brand')) { //if there is a key of brand in our src map
                            typeOfCard = (String)src.get('brand'); //grab the value for the brand key from the src map and cast it to a string
                        }
                        if (src.containsKey('last4')) { //if there is a key of last4 in our src map
                            last4OfCard = (String)src.get('last4'); //grab the value for the last4 key from the src map and cast it to a string
                        }
                    }
                    
                    responseJSON.contactid = queriedContacts[0].Id; //populate the Id of the Contact record to our response object
                    
                    Task newTask = new Task(ActivityDate = Date.Today(), Description = 'The '+typeOfCard+' credit card ending in '+last4OfCard+' was charged.', Status = 'Complete', Subject = typeOfCard+' Card Charged', WhoId = queriedContacts[0].Id); //create a Task
                    
                    Database.SaveResult insertNewTask = Database.insert(newTask); //insert the new Task
                    if (!insertNewTask.isSuccess()) { //if the insert DML was NOT successful
                        List<Database.Error> errors = insertNewTask.getErrors(); //grab the error array from the SaveResult object
                        //respond with failure
                        responseJSON.status = 'failure';
                        responseJSON.message = errors[0].getMessage(); //set the message to the first error in the array
                    } else { //otherwise, the insert was successful
                        responseJSON.taskid = insertNewTask.getId(); //populate the Id of the Task record to our response object
                    }
                } else { //otherwise, no key of source in our map
                    //respond with failure
                    responseJSON.status = 'failure';
                    responseJSON.message = 'There are no Contacts with the email address of '+emailAddress+'.';
                }
            } else { //otherwise, no key of description in our map
                //respond with failure
                responseJSON.status = 'failure';
                responseJSON.message = 'No description in the JSON request.';
            }
        } else { //otherwise, the JSON body was white space, empty ('') or null
            //respond with failure
            responseJSON.status = 'failure';
            responseJSON.message = 'Things basically broke...';
        }
        return responseJSON; //return the JSON response
    }
    
    //wrapper class for the response to an API request
    global class responseWrapper {
        
        global String status {get;set;} //status string
        global String contactid {get;set;} //18 character Contact record Id
        global String taskid {get;set;} //18 character Task record Id
        global String message {get;set;} //message string
        
        //constructor
        global responseWrapper() {
            //default all values
            this.status = 'success';
            this.contactid = '';
            this.taskid = '';
            this.message = '';
        }
    }

}

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
​Raj
Radhe Shyam.Radhe Shyam.
Thank you guys..
Maharajan CMaharajan C
Hi Radhe,

Close this thread by the choosing the best one which helps you!!!

Thanks,
raj