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
Raghu RamanujamRaghu Ramanujam 

Help With Rest Api Callout

Dear All,

I need some help in making a Rest Api Call Out.
When I execute the below code in Execute Anonymous Window, it works fine.

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://XXXX-dev.XXXXXXX/PSSSSSb/zzzzz/EZApiDEGroupDEVMain/invoice/compsearch');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{ "company_reg": "06587726"}');

HttpResponse response = http.send(request);

if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
    System.debug('Response ' + response.getBody());
} else {
    System.debug(response.getBody());
}


But when the tried to put this in a Apex class, its not working. (status code == 500)

public with sharing class ProvenirCsCallout {
    
    @future (callout=true)
    public static void sendRequest(Id accid, String comp_reg){
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
            request.setEndpoint('https://xxxxxxxx/xxxx/xxxxxxEZApiDEGroupDEVMain/invoice/compsearch');
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/json;charset=UTF-8');
            //request.setHeader('Accept','application/json');
// Set the body as a JSON object
            JSONGenerator gen = JSON.createGenerator(true);   
                gen.writeStartObject();     
                gen.writeStringField('company_reg ', comp_reg);
                String jsonS = gen.getAsString();
            
                request.setBody(jsonS);
           // request.setBody('company_reg='+EncodingUtil.urlEncode(comp_reg, 'UTF-8'));

            HttpResponse response = http.send(request);
     
            if(response.getstatusCode() == 200 && response.getbody() != null){
               String strResponse = Response.getBody();
                } else {
}

What I am missing ???

Thanks,
Raghu
Sumeet_ForceSumeet_Force
1. Check if both endpoints referenced are correct.
2. The JSON that gets generated in second part...check using debug.print for request.getBody() if its the same as the first.
Raghu RamanujamRaghu Ramanujam
Thanks Sumeet.
I solved it .. typo
gen.writeStringField('company_reg ', comp_reg);
removed the space after 'Company_reg'