Fetch Records By LIST VIEW Id In Apex

by Rijwan Mohmmed
fetch-records-by-list-view-id-in-apex

Hello friends, today we are going to discuss Fetch Records By LIST VIEW Id In Apex. A LIST view is essentially a filtered and organized representation of data in a Salesforce object. It allows users to define a set of criteria and sorting options to display only the records that meet those criteria. LIST views are commonly used to provide users with a focused and customizable view of data.

One common task in Apex development is retrieving records from a Salesforce object based on specific criteria. While SOQL (Salesforce Object Query Language) is commonly used for querying data, there’s an often overlooked approach that can simplify the process – fetching query results by using a LIST view ID.

Also, check this: Invoke Tooling API From LWC Salesforce

Key Highlights :

  1. We use Tooling API to fetch query of any LIST view Id and then execute.
  2. Tooling API allows developers to dynamically query metadata information using SOQL.
  3. We can call Tooling API by REST API in APEX.
  4. Use Userinfo.GetSessionId for Authorization.

Code :

ListViewsResponse.cls :

/**
 * @description       : This class represents the response recieved from the List View APIs which the Salesforce offers.
 * @coverage          : Test.cls | @CC100%
 * @author            : techdicerkeeplearning@gmail.com
 * @group             : Techdicer
 * @last modified on  : 05-27-2023
 * @last modified by  : techdicerkeeplearning@gmail.com
 * Modifications Log
 * Ver   Date         Author                                    Modification
 * 1.0   05-27-2023   techdicerkeeplearning@gmail.com             Initial Version | Story Number | @CC100%
 **/
public class ListViewsResponse {
    public Boolean done;
    public List<ListView> listviews;
    public Object nextRecordsUrl;
    public Integer size;
    public String sobjectType;

    public class ListView {
        public String describeUrl;
        public String developerName;
        public String id;
        public String label;
        public String resultsUrl;
        public Boolean soqlCompatible;
        public String url;
    }
    
    public static ListViewsResponse parse( String json ) {
        return ( ListViewsResponse ) System.JSON.deserialize( json, ListViewsResponse.class );
    }
}

ListViewsDescribeResponse.cls :

public class ListViewsDescribeResponse {

	public class OrderBy {
		public String fieldNameOrPath;
		public String nullsPosition;
		public String sortDirection;
	}

	public List<Columns> columns;
	public String id;
	public List<OrderBy> orderBy;
	public String query;
	public String scope;
	public String sobjectType;
	public WhereCondition whereCondition;

	public class Columns {
		public String ascendingLabel;
		public String descendingLabel;
		public String fieldNameOrPath;
		public Boolean hidden;
		public String label;
		public String selectListItem;
		public String sortDirection;
		public Integer sortIndex;
		public Boolean sortable;
		public String type;
	}

	public class WhereCondition {
		public List<Conditions> conditions;
		public String conjunction;
	}

	public class Conditions {
	}

	
	public static ListViewsDescribeResponse parse(String json) {
		return (ListViewsDescribeResponse) System.JSON.deserialize(json, ListViewsDescribeResponse.class);
	}
}

ListViewAPI.cls :

/**
 * @description       : This class is created to make calls to List View APIs which Salesforce offers to get the List View details of a particular object.
 * @coverage          : Test.cls | @CC100%
 * @author            : techdicerkeeplearning@gmail.com
 * @group             : Techdicer
 * @last modified on  : 05-27-2023
 * @last modified by  : techdicerkeeplearning@gmail.com
 * Modifications Log
 * Ver   Date         Author                                    Modification
 * 1.0   05-27-2023   techdicerkeeplearning@gmail.com             Initial Version | Story Number | @CC100%
 **/

public class ListViewAPI {
    /**
     * @description This method is created to call the getListViewQuery method fetch query and query the data
     * @author techdicerkeeplearning@gmail.com | 05-27-2023 | Story Number
     **/
    public static void fetchDataAccordingListView(){
        String query = getListViewQuery('00B6F00000BMrbT', 'Contact');
        List<Sobject> SObjectList = Database.query(query);
        System.debug('SObjectList==> ' + SObjectList);
    }
    
    /**
     * @description This method is created to make request to the List View APIs with the object name to get the List Views in that object.
     * @author techdicerkeeplearning@gmail.com | 05-27-2023 | Story Number
     * @param sObjectName The name of the Object  whose List Views are  required.
     * @param ListViewsResponse Returns an instance of the 'ListViewsResponse' class which contains the List Views existing in the selected Object.
     * @return ListViewsResponse
     **/
    public static ListViewsResponse getListViews(String sObjectName) {
        Http http = new Http();
        HttpRequest httpReq = new  HttpRequest();
        
        String orgDomain = Url.getSalesforceBaseUrl().toExternalForm();
        
        String endpoint = orgDomain + '/services/data/v37.0/sobjects/' + sObjectName + '/listviews';
        
        httpReq.setEndpoint(endpoint);
        httpReq.setMethod('GET');
        httpReq.setHeader('Content-Type', 'application/json; charset=UTF-8');
        httpReq.setHeader('Accept', 'application/json');
        
        String sessionId = 'Bearer ' + UserInfo.getSessionId();
        
        httpReq.setHeader('Authorization', sessionId);
        
        HttpResponse httpRes = http.send(httpReq);
        
        ListViewsResponse listViewResp = (ListViewsResponse) JSON.deserialize( httpRes.getBody(), ListViewsResponse.class);
        
        return listViewResp;
    }
    
    /**
     * @description This method is created to get the Query to obtain records from a particular object
     * @author techdicerkeeplearning@gmail.com | 05-27-2023 | Story Number
     * @param listViewId Recieves the List View Id whichever the User wants.
     * @param objName The name of the SObject.
     * @return String Returns the query for the particular List View.
     **/
    public static String getListViewQuery(String listViewId, String objName) {
        Http http = new Http();
        HTTPRequest httpReq = new HTTPRequest();
        String orgDomain = Url.getSalesforceBaseUrl().toExternalForm();
        
        String endpoint = orgDomain + '/services/data/v37.0/sobjects/' + objName + '/listviews/' + listViewId + '/describe';
        
        httpReq.setEndpoint( endpoint );
        httpReq.setMethod( 'GET' );
        httpReq.setHeader( 'Content-Type', 'application/json; charset=UTF-8' );
        httpReq.setHeader( 'Accept', 'application/json' );
        
        String sessionId = 'Bearer ' + UserInfo.getSessionId();
        
        httpReq.setHeader( 'Authorization', sessionId );
        
        HTTPResponse httpRes = http.send(httpReq);
        System.debug(httpRes.getBody());
        if(httpRes.getStatusCode() == 200){
            ListViewsDescribeResponse listViewDescResp = (ListViewsDescribeResponse) JSON.deserialize(httpRes.getBody(), ListViewsDescribeResponse.class);
            return listViewDescResp.query;
        } else{
            return '';
        }
    }
}

Output :

Reference :

  1. Tooling API
  2. List View
What’s your Reaction?
+1
1
+1
2
+1
0
+1
0
+1
1
+1
2

You may also like

2 comments

SM January 3, 2024 - 12:30 pm

I called method fetchDataAccordingListView( i.e. getListViewQuery) from the Aura init method and it gave me 401 status code. Session Id authentication not working as expected

Reply
Rijwan Mohmmed January 3, 2024 - 3:26 pm

Hi @SM, by Aura component you can not use UserInfo.getSessionId()
You can create VF page and get session Id in apex. you can take reference from below blog
https://techdicer.com/invoke-tooling-api-from-lwc-salesforce/

Reply

Leave a Comment