Here is REST handler.

@RestResource(urlMapping='/UpdateContact/*') global with sharing class REST_ParticipantHandler {

global static void updateParticipant() {

    //rest context variable initialization.
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;
    //utill class returns fieldmap from the custom setings
    Map<String,String> FieldMap=util.getFieldMap();
    Map<String,String> FieldTypeMap=util.getFieldTypeMap();
    Map<String, Object> jsonBodyMap = (Map<String, Object>)JSON.deserializeUntyped(req.requestBody.toString());
    Blob body = req.requestBody;
    String bodyString = body.toString();
    Wrapclass deserializedinput = (Wrapclass)JSON.deserialize(bodyString, Wrapclass.class);
    Map<String, Object> jsonBodyMapLcase = new Map<String, Object>();
    string qFields=String.join(FieldMap.values(), ', ');
    string uNum=''; 
    String sf_jsonResponse = '';
    //converting jSON body map keys into lowercase to handle casesensitity issues.
    for( string s1:jsonBodyMap.keySet()){

    //getting the userNum from Jsonbody to instantiate corresponding participant record.
        uNum = !string.IsBlank((String)jsonBodyMap.get('userNum'))?String.valueOf((String)jsonBodyMap.get('userNum')):'';

    // No userNum parameter was found; return status 400
    if(uNum == null) {
        res.statusCode = 400;
        sf_jsonResponse = '{"response": {"status": "Failure", "message": "MissingRequiredQueryParameter userNum"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);
    //Dynamic query to query the object dynamically with all the fields.
    string query ='SELECT ' + qFields
                   + ' FROM contact'
                   + ' WHERE user_num__c = \'' + String.escapeSingleQuotes(uNum) + '\''
                   + ' LIMIT 1';
    List<Contact> parts=Database.query(query);
    // No Participants with matching userNum
    if( parts.size()<=0) {
        res.statusCode = 400;
        sf_jsonResponse = '{"response": {"status": "Failure", "message": "No matching Participant record:'+uNum+' ' +'found with this userNum"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);
    //participant Instance
    contact p=parts.get(0);

    for(String pfield:FieldMap.keySet()){


            if('Text'==FieldTypeMap.get(pfield))    {

            else if('Currency'==FieldTypeMap.get(pfield)){

            else if('Number'==FieldTypeMap.get(pfield))  {

            else if('Date'==FieldTypeMap.get(pfield))    {
                system.debug(LoggingLevel.error,'Field=' + FieldMap.get(pfield));
                //Data coming as a string value with '-' seprator and salesfore wont accept the string to date field. needs to convert string to salesforce date formate.
                string sDate=string.valueOf((String)jsonBodyMapLcase.get(pfield));
                system.debug(LoggingLevel.error,'sDate**=' + sDate);
                //date d =util.getDateSfFormate(sdate);
                String[] myDateOnly = sDate.split(' ');
                String[] strDate = myDateOnly[0].split('-');
                Integer myIntYear = integer.valueOf(strDate[0]);
                Integer myIntMonth = integer.valueOf(strDate[1]);
                Integer myIntDate = integer.valueOf(strDate[2]);
                Date dt= Date.newInstance(myIntYear, myIntMonth, myIntDate);
                system.debug(LoggingLevel.error,'dt**=' + dt);
            else if('Checkbox'==FieldTypeMap.get(pfield)){
                else {
    system.debug(LoggingLevel.error,'updated Participant=' + p);

    try {
        res.statusCode = 200;
        update p;
        sf_jsonResponse = '{"response": {"status": "Sucess", "message": "Participant record:'+uNum +' ' +'is updated in Salesforce"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);
    } catch ( Exception ex ) {
        res.statusCode = 500;
        sf_jsonResponse = '{"response": {"status": "Failure", "message": "Participant record:'+uNum +' '+ ex + '"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);

 global class Wrapclass {
    public String status;
    public String responseBody;



Here is my Test class..

@isTest(seeAllData=false) Public class Test_RESTParticipantHandler {

public static testMethod void testdoPost() {

    System.RestContext.request = new RestRequest();
    System.RestContext.response = new RestResponse();

    Account a = new Account(Name = 'Test', RK_ID__c='106',PR_FE_Branded__c= true);
    insert a;
    String orgId=a.id;

    Contact c = new Contact();

    c.firstname = 'Wain';
    c.lastname = 'R';
    c.AccountId = orgId;
    c.email = 'Wain@test.com';
    c.phone = '6884382997';
    c.mailingstreet = '123 Test Ave';
    c.mailingcity = 'Somewhere';
    c.mailingstate = 'MA';
    c.mailingPostalCode = '87945';
    c.mailingcountry = 'US';

    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    REST_ParticipantHandler.Wrapclass reqst=new REST_ParticipantHandler.Wrapclass();
    reqst.status= 'Success';
    reqst.responseBody ='{"state":"CA","riskTolerance":"Typical for your age","retirementAge":"70",alPortfolio":"65627.50","phoneContactPreference":"SEC Required Only","email":"","homePhone":"5555555555","title":"","mailingAddress":"13630 SE 231ST ST","userNum":"13328911","lastInitial":"R","city":"Sunnyvale","zip":"94086","foreignResident":"0","workPhone":"4084986934","otherPhone":"5555555555",","isFeBrand":"1","primaryAccountPlan":"Voluntary Investment Plan (VIP)","convertedFromUserNum":"","convertedToUserNum":"","countryCode":"US"}';
    String JsonMsg=JSON.serialize(reqst);

    req.requestURI ='/services/apexrest/UpdateParticipant'; 
    req.httpMethod = 'POST';
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.response= res;
    RestContext.request = req;

    //System.assertEquals('true', results.success);
    //System.assertEquals(10, results.records.size());



Im getting an error "System.QueryException: unexpected token: 'FROM'"


The issue is in the qFields check this line -

string qFields=String.join(FieldMap.values(), ', ');

Its adding comma after each field api name so your effective query comes like -

Select Id, Name, Email, FROM Contact 

Notice the extra comma after Email. So you may have to write a method to replace the eliminate the last comma from qFields something like below (where I add below line after the String.Join line)-

qFields = qFields.substring(0, value.length-1)

This will eliminate the current error.

  • Thanks for your response Amit, i was able to resolve the query issue. but still the code coverage is 40%. its skipping below lines of code, im actually setting status code and jsonpayload has the usernum but it is still skipping below if block if(uNum == null) { res.statusCode = 400; sf_jsonResponse = '{"response": {"status": "Failure", "message": "MissingRequiredQueryParameter userNum"}}'; – KrForce Aug 18 '15 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.