Dynamic REST API JSON Body Using Field Sets in Apex

Question:
I need to construct the request body for a REST POST call in which the key (Field API Name) and its corresponding value are dynamically included in JSON format. The field API names are retrieved from a field set, and the values come from a database query.
For example, the request body should look like this:
{
"SubscriberAttributes": {
"Id": "001XXXXXXXXXXXXXXX",
"Trigger_DEMLTNR__c": "Value1",
"Order_number_DEORDNR__c": "Value2",
"Country_code__c": "Value3",
"Invoice_number_DEFAKNR__c": "Value4",
"MiddleName_DEKLVNM__c": "Value5",
"FirstName_DEKLAVN__c": "Value6",
"LastName_DEKLANM__c": "Value7",
"Email_encrypted__c": "Value8"
}
}
How can I dynamically create this JSON structure in Apex using the field set and database query?
Accelerate your Salesforce career with expert-led Salesforce training in Hyderabad, featuring hands-on projects and guidance for beginners and professionals.
Answer:
To achieve this, you can use Apex to retrieve the fields from a field set, dynamically query the data for those fields, and construct the JSON request body. Below is a step-by-step explanation with the relevant code.
Step 1: Retrieve Field Set Members
Retrieve the fields from the specified field set using the Schema.SObjectType.<Object>.fieldSets
API.
Schema.FieldSet fieldSet = Schema.SObjectType.Account.fieldSets.getMap().get('YOUR_FIELD_SET_NAME');
List<Schema.FieldSetMember> fieldSetMembers = fieldSet.getFields();
The code retrieves the field set for the Account
object using Schema.SObjectType.Account.fieldSets.getMap()
, specifying the field set name. It then accesses the list of FieldSetMember
objects from the field set using the getFields()
method. These members represent the fields defined in the field set. This allows dynamic access to the field names for further operations, such as constructing SOQL queries or generating request bodies. Replace Account
with the relevant object name and 'YOUR_FIELD_SET_NAME'
with your field set’s API name.
Step 2: Generate a Dynamic SOQL Query
You can build a dynamic SOQL query using the field set members. The following helper class can be used to construct and execute the query.
public with sharing class SoqlQueryHelper {
public static String buildQuery(SObjectType sObjectType, List<Schema.FieldSetMember> fieldSetMembers) {
if (fieldSetMembers == null || fieldSetMembers.isEmpty()) {
return null;
}
String query = 'SELECT ';
for (Schema.FieldSetMember field : fieldSetMembers) {
query += field.getFieldPath() + ', ';
}
query = query.removeEnd(', ') + ' FROM ' + sObjectType.getDescribe().getName() + ' LIMIT 1';
return query;
}
public static List<SObject> executeQuery(String soqlQuery) {
return Database.query(soqlQuery);
}
}
The SoqlQueryHelper
class builds and executes dynamic SOQL queries based on field set members. The buildQuery
method generates a query string by looping through the field set members and appending their field paths to the SELECT clause. It then adds the object type and limits the result to one record. The executeQuery
method executes the constructed query and returns the result as a list of SObject
records.
You can use this helper to generate and execute the query:
String query = SoqlQueryHelper.buildQuery(Schema.SObjectType.Account, fieldSetMembers);
List<SObject> records = SoqlQueryHelper.executeQuery(query);
The code generates a dynamic SOQL query using the field set members and executes it to retrieve records from the Account object. The query is built with the field names from the field set, and the results are stored in the records
list.
Step 3: Construct the JSON Request Body
Serialize the queried data into a JSON object. You can dynamically map the field names from the field set to their corresponding values in the queried SObject record.
Map<String, Object> subscriberAttributes = new Map<String, Object>();
if (!records.isEmpty()) {
SObject record = records[0];
for (Schema.FieldSetMember field : fieldSetMembers) {
String fieldName = field.getFieldPath();
subscriberAttributes.put(fieldName, record.get(fieldName));
}
}
Map<String, Object> requestBody = new Map<String, Object>();
requestBody.put('SubscriberAttributes', subscriberAttributes);
String jsonBody = Json.serialize(requestBody);
The code creates a map (subscriberAttributes
) to dynamically store field values from a queried record based on field set members. It then serializes the map into a JSON body (jsonBody
) for use in a REST API call.
Step 4: Use the JSON in the HTTP Request
You can include the JSON in the body of your HTTP POST request like this:
HttpRequest restRequest = new HttpRequest();
restRequest.setEndpoint('https://api.example.com/endpoint');
restRequest.setMethod('POST');
restRequest.setHeader('Content-Type', 'application/json');
restRequest.setBody(jsonBody);
Http http = new Http();
HttpResponse response = http.send(restRequest);
The code creates an HttpRequest
object to initiate a POST request. It sets the request endpoint, HTTP method (POST), and content type as JSON. The body of the request is populated with the jsonBody
variable, which contains the JSON data. Finally, the request is sent using the Http
class, and the response is captured in the HttpResponse
object.
Alternate Approach Using Map Serialization
If you want to avoid creating a helper class, you can directly loop through the field set members to build a Map
and serialize it. However, this approach might be less reusable.
This solution dynamically constructs the request body based on the field set and the queried data. It ensures the API names from the field set and their respective values are correctly populated in the JSON structure for the POST call.
Summing Up
Creating a dynamic REST API JSON body using field sets in Apex empowers developers to construct flexible and reusable integrations. By leveraging field sets, you can dynamically retrieve field API names and their corresponding values from the database, ensuring adaptability as requirements evolve. This approach involves generating SOQL queries based on field set members, mapping the retrieved data into a structured format, and serializing it into JSON for seamless REST API communication. This method not only simplifies handling dynamic fields but also promotes cleaner, modular code that can adapt to changes without hardcoding, making it a robust solution for scalable API integrations.
Kickstart Your Salesforce Career with Training in Hyderabad
Ready to boost your career with Salesforce? CRS Info Solutions offers top-tier Salesforce training in Hyderabad, designed to provide you with the skills needed to excel in the dynamic Salesforce ecosystem. Our expert-led courses cover critical modules like Salesforce Admin, Developer, and AI, with an emphasis on real-time project experience to ensure you gain hands-on expertise. Whether you’re a beginner or an experienced professional, our training prepares you for the challenges of the Salesforce world.
Our Salesforce training in Hyderabad focuses on practical, industry-relevant learning. With personalized guidance, comprehensive course materials, and expert support for certification and interview prep, we make sure you’re job-ready.
Enroll today for a free demo session and take the first step towards a successful Salesforce career!!!