Question
It is common for developers to wonder if existing Salesforce reports and their data can be accessed directly in Apex, instead of replicating the report logic with SOQL queries. Manually writing SOQL queries would require code changes every time the report is updated, which is not efficient. So the question is: is there a way to programmatically access Salesforce reports and their data?
Answer
The answer is yes. Salesforce introduced the Analytics REST API (also called the Salesforce Reports and Dashboards REST API), which allows developers to access report data programmatically. This API was first piloted in Summer ’13 and became generally available in Winter ’14. It lets you run reports, retrieve report metadata, and access report results directly in a structured format.
The Analytics REST API
Salesforce introduced this feature in a pilot during Summer ’13, and it became generally available in Winter ’14. The Analytics API was one of the most anticipated releases for developers, as it finally provided an official way to access report data in a structured manner.
With this API, you can do the following:
Access Record Details and Summaries: The API returns not just aggregated values but also row-level data, which can be used in custom logic or external integrations.
Run Reports programmatically: You can execute an existing report using its report ID and fetch the results in JSON format.
Retrieve Metadata: You can extract details about how the report is structured—fields, filters, groupings, and summary formulas.
The API endpoint looks like this:
/services/data/vXX.X/analytics/reports/{reportId}
This call returns a JSON response that contains both detail rows and aggregate values. That means if an admin changes the report by adding a new filter or column, your API call will reflect those changes automatically—no code changes required.
Older Unofficial Methods
Before the Analytics API existed, developers often relied on unsupported workarounds to access report data. One common approach was to export report data directly using the report’s URL, with export parameters for CSV or HTML. For example:
https://instance.salesforce.com/00Ox0000000xxxx?export=1&enc=UTF-8&xf=csv
his would return the report data in CSV format, which could then be parsed in Apex or another environment. Developers even discovered how to apply filters by passing query string parameters like pv0, pv1, and so on.
However, this approach came with serious drawbacks:
- It was not officially supported by Salesforce, so it could stop working at any time.
- With Lightning Experience enabled, these direct URL exports often failed because Salesforce redirected them to Lightning pages instead of returning raw data.
- Relying on undocumented URLs could cause compatibility issues and even raise concerns about Salesforce’s terms of service.
Because of these risks, while this method worked for some projects, it was never suitable for long-term or enterprise-grade solutions.
The Recommended Approach
Salesforce now strongly recommends using the Analytics REST API as the official and supported way to access report data programmatically. It is reliable, future-proof, and designed specifically for these use cases. Developers should avoid relying on direct URL exports because they are fragile and may break at any time.
With the Analytics API, you can safely integrate report data into Apex, Lightning Components, or even external systems like a custom dashboard or third-party application. This gives you the flexibility to mirror report results exactly as they are configured by admins, without maintaining duplicate SOQL queries.
Example: Running a Report with the Analytics REST API
Here’s a simplified Apex example showing how you might call the Analytics API to run a report and fetch results.
public class ReportDataFetcher {
public static void fetchReportData(String reportId) {
// Define the API endpoint for the report
String endpoint = URL.getSalesforceBaseUrl().toExternalForm() +
'/services/data/v57.0/analytics/reports/' + reportId;
// Prepare the HTTP request
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
req.setHeader('Content-Type', 'application/json');
// Send the request
Http http = new Http();
HttpResponse res = http.send(req);
// Check the response
if(res.getStatusCode() == 200) {
System.debug('Report Data: ' + res.getBody());
} else {
System.debug('Error: ' + res.getStatus() + ' - ' + res.getBody());
}
}
}
Code Explanation (in 4 lines)
- The method builds the REST API endpoint dynamically using the Salesforce base URL and the given report ID.
- An HTTP request is prepared with the session ID for authentication and JSON headers.
- The request is sent using the
Httpclass, and the response is captured. - If successful, the method logs the report data in JSON format; otherwise, it prints the error.
This approach allows you to keep using reports as they are defined by admins, while still being able to integrate that data into custom logic. Instead of rewriting SOQL every time a report changes, you simply call the report by its ID and let Salesforce handle the updates.
Job-Oriented Salesforce Training with 100% Money Back Guarantee
Our Salesforce course is meticulously designed to equip you with a thorough understanding of the Salesforce platform, helping you develop the essential skills needed for success in the CRM industry. The program covers vital modules such as Salesforce Admin, Developer, and AI, combining theoretical knowledge with hands-on experience. Through engaging in real-world projects and assignments, you will build the expertise necessary to solve business challenges using Salesforce solutions. Our seasoned instructors ensure you gain the technical skills and practical insights to excel within the Salesforce ecosystem.
Along with building technical proficiency, our Salesforce training in India offers personalized mentorship, exam preparation, and interview coaching to enhance your career prospects. You’ll have access to extensive study resources, practical exposure, and unwavering support throughout your learning journey. By the end of the course, you’ll be fully prepared for certification exams and equipped with the problem-solving abilities that employers value. Start your Salesforce career today and open the door to endless opportunities. Sign up for a free demo now!





Leave a Reply
You must be logged in to post a comment.