+ Start a Discussion
sakshi Gandhi 8sakshi Gandhi 8 

Sending JSON in Http request using Apex

I have below JSON ,How can I send in my request using apex:

"objects":[
{
"fieldsToNull":["DefaultPaymentMethodId"],
"AccountNumber":"A00000036",
"Id":"2c92c0f95a4085a8015a41f4012d183e"
}
]
, "type":"Account"
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Sakshi,

Use the HttpRequest class to programmatically create HTTP requests like GET, POST, PUT, and DELETE.May I request you please refer the below link for reference. Hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Thanks
Rahul Kumar
sakshi Gandhi 8sakshi Gandhi 8
I need to know how will I pass JSON in body of my request?
PawanKumarPawanKumar
Hi Sakshi,
Please try below.

  String jsonBody = 'your json body';

  //Set HTTPRequest Method
  HttpRequest req = new HttpRequest();
  req.setMethod('POST');
  req.setHeader('Accept-Encoding', 'gzip,deflate');
  req.setHeader('content-type', 'text/xml; charset=utf-8');
  req.setHeader('Content-Length', String.valueOf(jsonBody.length()));
  req.setEndpoint('Rest URL');

  // setting body
  System.debug('Input Request:' + jsonBody);
  req.setBody(jsonBody);

  //Execute web service call here     
  Http http = new Http();
  HTTPResponse res = http.send(req);

  //Helpful debug messages
  System.debug(res.toString());
  System.debug('STATUS:' + res.getStatus());
  System.debug('STATUS_CODE:' + res.getStatusCode());
  String responseXML = res.getBody();
  System.debug('responseXML:' + responseXML);

Regards,
Pawan Kumar
PawanKumarPawanKumar
Please let me know if it works for you
sakshi Gandhi 8sakshi Gandhi 8
How to create a json body this is my question here rest I have done authentication is done.
PawanKumarPawanKumar
Cool Sakshi.

I have implemented below in one of my project to generate JSON. Might be this could be helpful for you.

// save as class
public class RPSCaseContainer {
    public List < Case > cases{
        get;
        set;
    }
}

// save as class
public without sharing class RPSJsonRequestGenerator {
    public static String generateJson(Set<String> caseIds, Boolean hasNull) {
        List < Case > cases = null;
           // you change field as per your your instance
            cases = [SELECT Id,AccountId,ContactId,RecordTypeId,ParentId,Type,Origin,Priority FROM Case where Id IN:caseIds];

        RPSCaseContainer  container = new RPSCaseContainer();
        if (!cases.isEmpty()) {
            container.cases = cases;
        }
        
        String jsonText = JSON.serialize(container, hasNull);
        System.debug('jsonText =' + jsonText);
        return jsonText;
    }
}

// run below in developer console as anonymous
Set<String> caseSet = new set<String>();
caseSet.add('YourCaseId');
System.debug(RPSJsonRequestGenerator.RPSJsonRequestGenerator(caseSet,false));

Regards,
Pawan Kumar
 
shrish mysoreshrish mysore
Hi,

Use JSONGenerator class to create your JSON Object and then convert it to string and set it as request body. Please refere below code, just to get you know the basics, please refere JSONGenerator class guide for more clarity/ information.
JSONGenerator jg = JSON.createGenerator(false); // set boolean value true if you want  pretty format applied

jg.writeStartObject();
jg.writeFieldName('objects');
jg.writeStartArray();
jg.writeStartObject();
jg.wrtitefieldName('fieldsToNull');
/* continue same as above according to your field's type. For this check out JSONGenerator Class */

HttpRequest req = new HttpRequest();

req.setBody( jg.getAsString() ); // convert to string and set it as body

Happy Coding !!!
NSK000NSK000
Hi Guys,

I'm trying to pass a parameter in the body. Please let me know what I 'm doing wrong!! I'm getting a 405 error.

payload should be part of http request body.
Example:
{
"Enter":"111111111"
}
Response data:
{
"Number":"22332221212",
"message":"Good Return",
}

Here is the code:

string body = 'Enter:111111111';
HttpRequest request = new HttpRequest();
request.setEndpoint('http://xxxx-api/v1.0/number');
request.setMethod('GET');
request.setHeader('client_id','xx'); 
request.setHeader('client_secret','xx'); 
request.setHeader('Content-Type','application/json;charset=UTF-8');
request.setBody(body);
Http http = new Http();
HttpResponse response = http.send(request);
//System.debug(response.getBody());
if (response.getStatusCode() != 200) {
  System.debug('The status code returned was not expected: ' +
       response.getStatusCode() + ' ' + response.getStatus());
} else {
   System.debug(response.getBody());
}
 
Yogesh BiyaniYogesh Biyani
@NSK000 were you able to resolve the 405 error?