[SalesForce] Status=Bad Request, StatusCode=400 on rest api call

I am hoping someone can tell me why I am getting a bad request when this executes

Here is my rest api code

@RestResource(urlMapping='/emailservices/*')
global class EmailInsert {

  @HttpPost 
  global static String addEmail(String fName, String fEmail, String pToAddress,
                                    String pSubject, String pTextBody, String cid) {
EmailMessage msg = new EmailMessage(FromName=fName, FromAddress=fEmail, ToAddress=pToAddress,
  Subject=pSubject, TextBody=pTextBody, ParentId=cid, MessageDate=System.now(),
  Incoming=true, Status='0');
insert msg;

return msg.Id;
  }
}

And here is the method that is calling it

  @future(callout=true)
  private static void DoCallout(String cid, String subj, String tbody)
  {
Map<String, String> jinp = new Map<String, String>();
jinp.put('fname','Service');
jinp.put('fEmail','noreply@acme.com');
jinp.put('pToAddress', UserInfo.getUserEmail());
jinp.put('pSubject', subj);
jinp.put('pTextBody', tbody);
jinp.put('cid', cid);     

String jsonInput = JSON.serialize(jinp);
    system.debug('JSON String: ' + jsonInput);
    // Call the web service to insert into Email Message object
    Http http       = new Http();
    HttpRequest req = new HttpRequest();

      req.
    req.setHeader('Content-Type', 'application/json');
    req.setEndpoint('https://<myinstance>.force.com/support/services/apexrest/emailservices');
    req.setMethod('POST');
    req.setBody(jsonInput);
    http.send(req);       
  }

When the call executes I end up with Status=Bad Request, StatusCode=400 in the debug logs I have looked at the formatted JSON String and it looks good.

Any thoughts as to why this fails?

Best Answer

Are you trying to call rest webservice exposed in another Salesforce org?. Because if both classes are in same org, you can just call the method directly instead of using webservice.

Also if you are trying to access webservice from a different salesforce org, you would need to authenticate against second org using Oauth

Also your end point looks wrong. Generally it will be like "https://rd-mevion.cs22.force.com/services/apexrest/emailservices" without support in between.

Checkout below post, https://developer.salesforce.com/forums/?id=906F000000099zbIAA

Related Topic