ID query string parameter call to RestResource results in error
Update
I was also able to make your HttpPost
method work by moving the creation to a @future
method.
@RestResource(urlMapping='/createLead/*')
global with sharing class CreateLeadRest{
@HttpPost
global static void doPost()
{
insertLead(RestContext.request.params.get('id'));
}
@future
public static void insertLead(String id)
{
Lead newLead = new Lead();
newLead.Company='test';
newLead.LastName='test';
newLead.Description=id;
insert newLead;
}
}
If you have conflicting @future
calls getting in the way, consider using a Queueable
implementation. You probably should develop a defensive asynchronous framework if you plan on executing asynchronous logic directly in your triggers. I know Dan Appleman has written a lot of material on the subject, and how to properly use an asynchronous framework is somewhat outside the scope of this question.
Original Answer
First of all, you should also look at this Stack Overflow
post: How are parameters sent in an HTTP POST request? URI parameters and POST
requests are fundamentally incompatible.
Instead, you should shoot for a pattern more similar to how the documentation lays out POST
requests in Creating REST APIs using Apex REST (Using POST, PUT and PATCH).
The way you would normally access POST
parameters via Apex REST
is more like:
@RestResource(urlMapping='/createLead/*')
global with sharing class CreateLeadRest{
@HttpPost
global static void doPost(String id) {
Lead newLead = new Lead();
newLead.Company='test';
newLead.LastName='test';
newLead.Description=id;
insert newLead;
}
}
Then if you pass the parameters through the Body, your request should succeed:
Summary
Method: POST
Endpoint: /services/apexrest/createLead/
Payload: {"id": 123}
Screenshot
Whereas any attempt to pass parameters via the URI should fail:
Summary
Method: POST
Endpoint: /services/apexrest/createLead/?id=123
Payload: {"id": 123}
Screenshot
The reason you're getting this error, is that Lead has required field LastName.
It seems that tool you're using is not providing full info, I would recommend to use Chrome extension Postman. That will give HTTP 500 and:
[ { "errorCode": "APEX_ERROR", "message": "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName]\n\nClass.CreateLeadRest.doPost: line 12, column 1" } ]
or you can add to your code something like:
url: https://naxx.salesforce.com/services/apexrest/createLead?id=50036000000xxxx
global static String doPost() {
//..
try {
insert newLead;
} catch (exception e){
return e.getMessage();
}
return newLead.id;