REST API with XML and JSON Both in Same Apex Class : jayakrishnasfdc

REST API with XML and JSON Both in Same Apex Class
by: jayakrishnasfdc
blow post content copied from  Jayakrishna Ganjikunta
click here to view original post


In Previous Example , have explained how to do REST API separately with XML and separately with JSON.

if we want to create both in same class and when third party use either of these to call from salesforce how we can create apex in salesforce explaining in this blog post.

Parsing xml in Apex : Converting XML into JSON or Deserializing XML – Sfcure

For this first we need to write an helper class where we can write both XML and JSON to return ( use deserialization)
and after we have to write separate class with REST API to call helper class.

Helper Class:

Global class RestHelper {
 public static blob formatResponse(ResponseBase ResponseBaseObj,String contentType){
        String response;
        String strContectType = contentType.toUpperCase();
        if(strContectType.contains('XML')){
            response = serializeResponseBaseXml(ResponseBaseObj);
        }    
        else {
            response = JSON.serialize(ResponseBaseObj);
        }
        return blob.valueOf(response);
    }


    public static string serializeResponseBaseXml(ResponseBase ResponseBaseObj ){
        String responseXML = '';
        responseXML  += '<response>';
        XmlStreamWriter w = new XmlStreamWriter();
        w.writeStartElement(null , 'Message', null );
        w.writeCharacters(ResponseBaseObj.Message);
        w.writeEndElement();
        
        w.writeStartElement(null , 'Success', null );
        w.writeCharacters(String.valueOf(ResponseBaseObj.Success));
        w.writeEndElement();
        responseXML += '</response>';
        String xmlOutput = '<?xml version="1.0" encoding="UTF-8"?>' + '<Response>' + w.getXmlString() 
            + '</Response>';
        w.close();
        return xmlOutput ;
    }

    global class ResponseBase {
        global Boolean Success {get;set;}
        global String Message  {get;set;}
        global ResponseBase(){
                success = true;
                message = 'Records are updated';
        }
    }
}

REST API:

@RestResource(urlMapping='/api/v1/ContactMgmt')
global with sharing class RestAPI 
{
    @HttpPost 
    global static void doPost(ContactDetail  Conct) {
    
        RestResponse standardResp = RestContext.response;
        RestHelper.ResponseBase  CustomeResponse = new RestHelper.ResponseBase(); 
        ContactDetail reqBodyObj = Conct; 

        RestRequest req = RestContext.request;       
        String ContentType = RestContext.request.headers.get('Content-Type') ;
        
        Contact cont = new Contact();
        cont.FirstName = reqBodyObj.FirstName.trim();   
        cont.LastName  = reqBodyObj.LastName.trim();
        cont.Phone  = reqBodyObj.Phone.trim();
        insert cont;
        
        CustomeResponse.Success = true;
        CustomeResponse.Message = 'Contact Created id ='+cont.id;
        standardResp.statusCode = 200;
        standardResp.responseBody = RestHelper.formatResponse(CustomeResponse,ContentType); 
            
    }

    global class ContactDetail{
       global string FirstName {get;set;}
       global string LastName  {get;set;}
       global string Phone  {get;set;}
       public ContactDetail()  {}
    }
}

Try with JSON

Request Body:

{
   "Conct": {
                "FirstName":"Jayakrishna",
                "LastName" :"Ganjikunta",
                "Phone" : 8867400396
         }
}

Try with XML

<request>
    <Conct>
        <FirstName>jayakrishna</FirstName>
        <LastName>Ganjikunta</LastName>\
        <Phone> 9949055222</Phone>
    </Conct>
</request>

January 03, 2021 at 04:27PM
Click here for more details...

=============================
The original post is available in Jayakrishna Ganjikunta by jayakrishnasfdc
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce