Saturday, August 2, 2025

Salesforce Integration Interview Questions For 5 Years Experience With Answers

1) What are the main differences between REST and SOAP APIs in Salesforce, and when would you choose one over the other?

Differences between REST and SOAP APIs:
Format and Simplicity:

  • REST API: Supports both JSON and XML formats. It is lightweight, easy to use, and well‑suited for modern web and mobile applications.

  • SOAP API: Supports only XML format, which can be more complex to handle.
    Protocol and Methods:

  • REST API: Uses standard HTTP methods such as GET, POST, PUT, DELETE, etc.

  • SOAP API: Relies on a strict XML messaging protocol and includes a WSDL (Web Services Description Language) file for communication.
    When to Choose:

  • Choose REST API when simplicity, speed, and modern formats like JSON are needed.

  • Choose SOAP API when integration demands more robust error handling, advanced security, or backward compatibility with older systems.

2) What is Salesforce Connect, and in what scenarios would you recommend using it for integration?
Salesforce Connect is a feature that allows users to access and display external data within Salesforce without storing it in Salesforce databases. It uses external objects to map to external data tables and accesses data on demand in real time.
Scenarios for Using Salesforce Connect:

  • Large Data Volumes: When you have large datasets that you don't want to replicate in Salesforce.

  • Real‑Time Data Access: When you need real‑time access to the latest external data instead of working with stale data copies.

  • Efficient Data Retrieval: When only small amounts of data are needed at a time, minimizing the need for storage and replication.
    Advantages:

  • Avoids data redundancy.

  • Ensures up‑to‑date and accurate information.

  • Simplifies integration with minimal data storage overhead.
    Example Use Case: A company might use Salesforce Connect to access customer data stored in an external ERP system, ensuring sales teams always have the most up‑to‑date order and account details without duplicating that data in Salesforce.

3) What is the Bulk API in Salesforce, and when should it be used?
The Bulk API is designed for handling large‑scale data operations asynchronously. It supports insert, update, delete, upsert, and query operations in batches, making it ideal for processing thousands or millions of records efficiently.
When to Use:

  • When working with large data sets (e.g., over 2,000 records).

  • For data migrations or regular bulk updates.

  • To optimize performance and avoid API call limits.

4) What is a Connected App in Salesforce, and why is it important for integration?
A connected app in Salesforce is designed to enable external applications to integrate with Salesforce APIs securely. For example:

  • To use OAuth authorization for external apps, configure the connected app with appropriate OAuth settings.

  • For SAML single sign‑on (SSO) flows, configure SAML settings.

5) What is Single sign‑on (SSO)?
Single sign‑on (SSO) is an authentication method that enables users to access multiple applications with one login and one set of credentials. For example, after users log in to your org, they can automatically access all apps from the App Launcher. You can set up your Salesforce org to trust a third‑party identity provider to authenticate users. Or you can configure a third‑party app to rely on your org for authentication.

6) What is identity provider and service provider? What are the different ways that I can implement SSO?
When you set up SSO, you configure one system to trust another to authenticate users, eliminating the need for users to log in to each system separately. The system that authenticates users is called an identity provider. The system that trusts the identity provider for authentication is called the service provider.
Salesforce supports SSO with SAML and OpenID Connect. Salesforce also has preconfigured authentication providers that you can use to enable SSO with systems that have their own authentication protocols, like Facebook.

7) What is the role of SAML in Salesforce Single Sign‑On (SSO), and how does it work between two Salesforce orgs?
SAML (Security Assertion Markup Language) enables Single Sign‑On (SSO) between applications. In a Salesforce SSO scenario, one Salesforce org acts as the Identity Provider (IdP), where the user logs in, and another Salesforce org acts as the Service Provider (SP), where the user is redirected after successful authentication. The IdP authenticates the user and sends a SAML assertion to the SP to grant access.

8) What is Just‑in‑Time (JIT) Provisioning in Salesforce, and how is it used in Single Sign‑On (SSO)?
Just‑in‑Time (JIT) Provisioning in Salesforce is a feature that automatically creates or updates user accounts in the Service Provider (SP) org during the Single Sign‑On (SSO) process. It simplifies user management by eliminating the need to pre‑create user accounts in the SP org.
How JIT Works:
The Identity Provider (IdP) sends user information in a SAML 2.0 assertion during the authentication process.
Salesforce processes this information using a JIT handler (Apex class) or standard JIT settings.
If the user does not already exist in the SP org, a new user account is created in real‑time.
Example Use Case:
In a multi‑org setup, if a user logs in to an Identity Provider org but their account does not exist in the SP org, JIT creates the account dynamically based on the information provided in the SAML assertion.

9) What are SAML Request, SAML Response, and SAML Assertion in the context of Single Sign‑On (SSO), and how do they function?
SAML Request:
When a user tries to access a Service Provider (SP), the SP sends a SAML Request to the Identity Provider (IdP).
This request asks the IdP to authenticate the user.
SAML Response:
After authenticating the user, the IdP sends a SAML Response back to the SP.
The response includes a signed SAML Assertion containing user details.
SAML Assertion:
A SAML Assertion is part of the SAML Response and asserts facts about the user, such as their username or email address.
The assertion is signed by the IdP to ensure its authenticity.
The SP validates this signature to confirm the integrity of the information.
How They Work Together:
The SAML Request initiates the SSO process.
The SAML Response conveys the authentication result.
The SAML Assertion provides the necessary user details to complete the authentication and grant access.
This process ensures secure, seamless user authentication between the Identity Provider and Service Provider.

10) What is an Identity Provider‑Initiated SAML Flow, and how does it work?
Identity Provider‑Initiated SAML Flow is a Single Sign‑On (SSO) process where the login begins at the Identity Provider (IdP).
Steps:
The user logs in to the identity provider.
The user clicks a button or link to access the service provider. For example, the user clicks an app on the App Launcher page in a Salesforce org.
The identity provider initiates login by sending a cryptographically signed SAML response to the service provider. The SAML response contains a SAML assertion that tells the service provider who the user is.
The service provider validates the signature in the SAML response and identifies the user.
The user is now logged in to the service provider.

11) What are the key steps involved in any OAuth authorization flow?
OAuth flows typically involve three main steps:
Access Request: The client app requests access to a protected resource.
Token Issuance: The authorization server grants an access token to the client app.
Token Validation: The resource server validates the access token and allows access to the protected resource.

12) How does the OAuth 2.0 Client Credentials Flow differ from the Username‑Password Flow?
OAuth 2.0 Client Credentials Flow: used for server‑to‑server integrations without user interaction. The client app exchanges its consumer key and consumer secret for an access token. More secure and avoids transmitting user credentials.
OAuth 2.0 Username‑Password Flow: authorizes a client app using stored user credentials. It is not recommended due to security risks, suitable only in special cases with a high degree of trust.

13) What makes the OAuth 2.0 JWT Bearer Flow secure, and when should it be used?
Security Features:
Uses a JSON Web Token (JWT) signed with a certificate, ensuring data integrity and authenticity.
Eliminates the need to transmit sensitive user credentials or rely on interactive logins.
Requires prior approval of the connected app, adding an additional layer of control.
Use Case:
Ideal for server‑to‑server integrations where ongoing access to Salesforce resources is needed without user interaction.

14) Why is the Username‑Password Flow not recommended, and what are its key steps?
The Username‑Password Flow is not recommended because it involves passing sensitive user credentials (username and password) back and forth, which can lead to security vulnerabilities, especially if the credentials are intercepted.
Key Steps:
The connected app sends a POST request to the Salesforce token endpoint with the user's credentials and app details (client ID, client secret, username, and password).
Salesforce verifies the request and grants an access token to the connected app.
The connected app uses the access token to access protected resources in Salesforce.

15) How can you integrate two Salesforce orgs using the Username‑Password Flow, and what are the main steps involved?
The integration of two Salesforce orgs using the Username‑Password Flow involves securely fetching data from one org (ORG B) and displaying it in another org (ORG A). This method leverages OAuth 2.0 for authentication and the Salesforce REST API for data retrieval.
Key Steps in Integration:
In ORG B: Create a Connected App to allow authentication. Implement a RESTful Web Service to fetch data.
In ORG A: Configure a Remote Site Setting to allow outbound calls to ORG B. Create an Apex Controller to authenticate with ORG B using the Username‑Password Flow and call the web service in ORG B to fetch the required data. Develop a Visualforce Page or LWC to display the retrieved information.

16) How would you integrate two Salesforce orgs using the Client Credentials Flow?
To integrate two Salesforce orgs using the Client Credentials Flow, follow these high‑level steps:
Setup in ORG B: Create a Connected App in ORG B, enabling the Client Credentials Flow to allow secure server‑to‑server communication; note consumer key/secret; implement web service in ORG B to handle incoming requests.
Setup in ORG A: Store credentials; configure Remote Site Settings; develop an Apex class to authenticate with ORG B and perform API callouts based on business rules; include error handling and logging.

17) What is the purpose of Salesforce Streaming API?
The Salesforce Streaming API enables real‑time data updates using push technology and an event‑driven architecture. It operates on an event‑based model, allowing applications to subscribe to events and receive updates as they occur in near real‑time.

18) What types of events are supported by the Salesforce Streaming API, and in which scenarios should it be used?
Types of Events Supported:
Generic Events: Legacy, for custom notifications.
PushTopics: Legacy, for changes in Salesforce records based on SOQL queries.
Change Data Capture (CDC): For tracking changes to Salesforce data records in real‑time.
Platform Events: For high‑volume, custom business event notifications.
When to Use the Streaming API:
Use Streaming API when real‑time data updates are required to synchronize external systems with Salesforce data, such as in applications that react immediately to changes in data or business processes.
Note: PushTopics and generic events are legacy products with limited support. For new implementations, use Change Data Capture instead of PushTopics and Platform Events instead of generic events.

19) What are platform events in Salesforce?
Platform events are secure and scalable messages used to enable real‑time communication between Salesforce and external apps, as well as within Salesforce itself, using an event‑driven messaging architecture.

20) What is the Event Bus in Salesforce?
The event bus is a temporary storage system where platform event messages are published. Events on the bus can be retrieved using a CometD client, and each event contains a ReplayId field to identify its position in the stream.

21) How can you publish a platform event using Apex?
You can publish a platform event using the EventBus.publish() method in Apex. Here's how:
Create an instance of the platform event object and populate its fields.
Use EventBus.publish() to publish the event, which returns a Database.SaveResult.
Check isSuccess() on the result to determine whether the event was published successfully.

TestEvent__e event = new TestEvent__e(
    Customer_Country__c = 'India',
    Customer_State__c = 'Maharashtra',
    Government_Customer__c = true
);
Database.SaveResult result = EventBus.publish(event);
if (result.isSuccess()) {
    System.debug('Platform event published successfully.');
} else {
    for (Database.Error error : result.getErrors()) {
        System.debug('Error: ' + error.getMessage());
    }
}

22) What is the difference between ReplayId and EventUuid in platform events?
ReplayId: A system‑assigned field that identifies the position of an event in the event stream. It isn’t guaranteed to be unique, especially during Salesforce maintenance activities.
EventUuid: A universally unique identifier (UUID) introduced in API version 52.0 and later. It is always unique and should be used to identify a platform event message.
Example of Retrieving EventUuid:
Database.SaveResult result = EventBus.publish(event);
if (result.isSuccess()) {
System.debug('UUID=' + EventBus.getOperationId(result));
}
Using EventUuid ensures the identification of an event message across different scenarios, including maintenance activities.

23) What are the Apex governor limits for platform event triggers?
Although platform event triggers run asynchronously, the synchronous limits apply to platform event triggers. This is because asynchronous limits are for long‑lived processes, such as Batch Apex and future methods. Synchronous limits are for short‑lived processes that execute quickly and platform event triggers are short‑lived processes that execute in batches rather quickly.
Because a platform event trigger runs in a separate transaction from the one that fired it, governor limits are reset, and the trigger gets its own set of limits.

24) How can you configure the user and batch size for a platform event trigger?
You can override the default running user and batch size of a platform event trigger using PlatformEventSubscriberConfig via Tooling API or Metadata API.
Default Configuration: Runs as the Automated Process user with a batch size of 2,000.
Custom Configuration: Specify a custom user and a batch size between 1 and 2,000. Smaller batch sizes help avoid hitting governor limits.

25) What is the High‑Volume Platform Event Hourly Publishing Allocation?
It specifies the maximum number of platform events that can be published in one hour. The limit is 250,000 events per hour for Performance and Unlimited Editions.

26) What publishing methods count toward the hourly publishing limit?
Publishing methods include:
Apex
Pub/Sub API
REST API
SOAP API
Bulk API
Flows
Process Builder processes

27) What happens if you exceed the hourly publishing limit?
Events published beyond the limit will fail. Organizations must monitor and optimize their event publishing to stay within the allowed limits.

28) What is Change Data Capture (CDC)?
Change Data Capture is a streaming product in Salesforce that enables real‑time integration with external systems. It notifies subscribed systems of data changes like record creation, updates, deletions, and undeletions, helping keep external systems in sync without periodic data exports or repeated API calls.

29) What types of objects support CDC?
CDC is available for all custom objects and a subset of standard objects. Each object has an associated ChangeEvent object, named ChangeEvent for standard objects and __ChangeEvent for custom objects.

30) Can CDC events be queried or modified?
No, ChangeEvent objects don’t support CRUD operations or queries. They are used to capture and publish changes but cannot be directly.

Salesforce Integration Interview Questions For 3 Years Experience With Answers

1) What are the main differences between REST and SOAP APIs in Salesforce, and when would you choose one over the other?

Differences between REST and SOAP APIs:
Format and Simplicity:

  • REST API: Supports both JSON and XML formats. It is lightweight, easy to use, and well-suited for modern web and mobile applications.

  • SOAP API: Supports only XML format, which can be more complex to handle.

Protocol and Methods:

  • REST API: Uses standard HTTP methods such as GET, POST, PUT, DELETE, etc.

  • SOAP API: Relies on a strict XML messaging protocol and includes a WSDL (Web Services Description Language) file for communication.

When to Choose:

  • Choose REST API when simplicity, speed, and modern formats like JSON are needed.

  • Choose SOAP API when integration demands more robust error handling, advanced security, or backward compatibility with older systems.

2) What is Salesforce Connect, and in what scenarios would you recommend using it for integration?

Salesforce Connect is a feature that allows users to access and display external data within Salesforce without storing it in Salesforce databases. It uses external objects to map to external data tables and accesses data on demand in real time.

Scenarios for Using Salesforce Connect:

  • Large Data Volumes: When you have large datasets that you don't want to replicate in Salesforce.

  • Real-Time Data Access: When you need real-time access to the latest external data instead of working with stale data copies.

  • Efficient Data Retrieval: When only small amounts of data are needed at a time, minimizing the need for storage and replication.

Advantages:

  • Avoids data redundancy

  • Ensures up-to-date and accurate information

  • Simplifies integration with minimal data storage overhead

Example Use Case: A company might use Salesforce Connect to access customer data stored in an external ERP system, ensuring sales teams always have the most up-to-date order and account details without duplicating that data in Salesforce.

3) What is the Bulk API in Salesforce, and when should it be used?

The Bulk API is designed for handling large-scale data operations asynchronously. It supports insert, update, delete, upsert, and query operations in batches, making it ideal for processing thousands or millions of records efficiently.

When to Use:

  • When working with large data sets (e.g., over 2,000 records)

  • For data migrations or regular bulk updates

  • To optimize performance and avoid API call limits

4) What is a Connected App in Salesforce, and why is it important for integration?

A connected app in Salesforce is designed to enable external applications to integrate with Salesforce APIs securely.
For example:

  • To use OAuth authorization for external apps, configure the connected app with appropriate OAuth settings
  • For SAML single sign-on (SSO) flows, configure SAML settings.                                        

5) What is Single sign-on (SSO)?
Single sign-on (SSO) is an authentication method that enables users to access multiple applications with one login and one set of credentials. For example, after users log in to your org, they can automatically access all apps from the App Launcher. You can set up your Salesforce org to trust a third-party identity provider to authenticate users. Or you can configure a third-party app to rely on your org for authentication.

6) What is the role of SAML in Salesforce Single Sign-On (SSO), and how does it work between two Salesforce orgs?
SAML (Security Assertion Markup Language) enables Single Sign-On (SSO) between applications. In a Salesforce SSO scenario, one Salesforce org acts as the Identity Provider (IdP), where the user logs in, and another Salesforce org acts as the Service Provider (SP), where the user is redirected after successful authentication. The IdP authenticates the user and sends a SAML assertion to the SP to grant access.

7) What is Just-in-Time (JIT) Provisioning in Salesforce, and how is it used in Single Sign-On (SSO)?
Just-in-Time (JIT) Provisioning in Salesforce is a feature that automatically creates or updates user accounts in the Service Provider (SP) org during the Single Sign-On (SSO) process. It simplifies user management by eliminating the need to pre-create user accounts in the SP org.

How JIT Works:
The Identity Provider (IdP) sends user information in a SAML 2.0 assertion during the authentication process.
Salesforce processes this information using a JIT handler (Apex class) or standard JIT settings.
If the user does not already exist in the SP org, a new user account is created in real-time.

Example Use Case:
In a multi-org setup, if a user logs in to an Identity Provider org but their account does not exist in the SP org, JIT creates the account dynamically based on the information provided in the SAML assertion.

8) What are SAML Request, SAML Response, and SAML Assertion in the context of Single Sign-On (SSO), and how do they function?

SAML Request:
When a user tries to access a Service Provider (SP), the SP sends a SAML Request to the Identity Provider (IdP).
This request asks the IdP to authenticate the user.

SAML Response:
After authenticating the user, the IdP sends a SAML Response back to the SP.
The response includes a signed SAML Assertion containing user details.

SAML Assertion:
A SAML Assertion is part of the SAML Response and asserts facts about the user, such as their username or email address.
The assertion is signed by the IdP to ensure its authenticity.
The SP validates this signature to confirm the integrity of the information.

How They Work Together:
The SAML Request initiates the SSO process.
The SAML Response conveys the authentication result.
The SAML Assertion provides the necessary user details to complete the authentication and grant access.
This process ensures secure, seamless user authentication between the Identity Provider and Service Provider.


9) What are the key steps involved in any OAuth authorization flow?

OAuth flows typically involve three main steps:

  1. Access Request: The client app requests access to a protected resource

  2. Token Issuance: The authorization server grants an access token to the client app

  3. Token Validation: The resource server validates the access token and allows access to the protected resource

10) What makes the OAuth 2.0 JWT Bearer Flow secure, and when should it be used?

Security Features:

  • Uses a JSON Web Token (JWT) signed with a certificate, ensuring data integrity and authenticity

  • Eliminates the need to transmit sensitive user credentials or rely on interactive logins

  • Requires prior approval of the connected app, adding an additional layer of control

Use Case:

  • Ideal for server-to-server integrations where ongoing access to Salesforce resources is needed without user interaction

11) How can you integrate two Salesforce orgs using the Username-Password Flow, and what are the main steps involved?

The integration of two Salesforce orgs using the Username-Password Flow involves securely fetching data from one org (ORG B) and displaying it in another org (ORG A). This method leverages OAuth 2.0 for authentication and the Salesforce REST API for data retrieval.

Key Steps in Integration:

In ORG B:

  • Create a Connected App to allow authentication

  • Implement a RESTful Web Service to fetch data

In ORG A:

  • Configure a Remote Site Setting to allow outbound calls to ORG B

  • Create an Apex Controller to:

    a) Authenticate with ORG B using the Username-Password Flow

    b) Call the web service in ORG B to fetch the required data

  • Develop a Visualforce Page or LWC to display the retrieved information

12) What is the difference between a self-signed certificate and a CA-signed certificate?

The main difference lies in the issuer of the certificate:

  • Self-Signed Certificate: Created, signed, and issued by the entity it is intended for. It does not involve any external validation

  • CA-Signed Certificate: Created, signed, and issued by a trusted third-party Certificate Authority (CA), which verifies the identity of the applicant

Key Consideration: CA-signed certificates are more widely trusted but come with a cost, while self-signed certificates are free but may not be trusted by external systems.

13) What is the purpose of Salesforce Streaming API?
The Salesforce Streaming API enables real-time data updates using push technology and an event-driven architecture. It operates on an event-based model, allowing applications to subscribe to events and receive updates as they occur in near real-time.

14) What types of events are supported by the Salesforce Streaming API, and in which scenarios should it be used?
Types of Events Supported:
Generic Events: Legacy, for custom notifications.
PushTopics: Legacy, for changes in Salesforce records based on SOQL queries.
Change Data Capture (CDC): For tracking changes to Salesforce data records in real-time.
Platform Events: For high-volume, custom business event notifications.

When to Use the Streaming API:
Use Streaming API when real-time data updates are required to synchronize external systems with Salesforce data, such as in applications that react immediately to changes in data or business processes.

Note: PushTopics and generic events are legacy products with limited support. For new implementations, use Change Data Capture instead of PushTopics and Platform Events instead of generic events.

15) What are platform events in Salesforce?
Platform events are secure and scalable messages used to enable real-time communication between Salesforce and external apps, as well as within Salesforce itself, using an event-driven messaging architecture.

16) What is the difference between ReplayId and EventUuid in platform events?
ReplayId: A system-assigned field that identifies the position of an event in the event stream. It isn’t guaranteed to be unique, especially during Salesforce maintenance activities.
EventUuid: A universally unique identifier (UUID) introduced in API version 52.0 and later. It is always unique and should be used to identify a platform event message.

Example of Retrieving EventUuid:
Database.SaveResult result = EventBus.publish(event);
if (result.isSuccess()) {
System.debug('UUID=' + EventBus.getOperationId(result));
}

Using EventUuid ensures the identification of an event message across different scenarios, including maintenance activities.

17) What are the Apex governor limits for platform event triggers?
Although platform event triggers run asynchronously, the synchronous limits apply to platform event triggers. This is because Asynchronous limits are for long-lived processes, such as Batch Apex and future methods. Synchronous limits are for short-lived processes that execute quickly and platform event triggers are short-lived processes that execute in batches rather quickly.

Because a platform event trigger runs in a separate transaction from the one that fired it, governor limits are reset, and the trigger gets its own set of limits.

18) How can you configure the user and batch size for a platform event trigger?
You can override the default running user and batch size of a platform event trigger using PlatformEventSubscriberConfig via Tooling API or Metadata API.
Default Configuration: Runs as the Automated Process user with a batch size of 2000.
Custom Configuration: Specify a custom user and a batch size between 1 and 2000. Smaller batch sizes help avoid hitting governor limits.

19) What is the High-Volume Platform Event Hourly Publishing Allocation?
It specifies the maximum number of platform events that can be published in one hour. The limit is 250000 events per hour for Performance and Unlimited Editions.

20) What publishing methods count toward the hourly publishing limit?
Publishing methods include:
Apex
Pub/Sub API
REST API
SOAP API
Bulk API
Flows
Process Builder processes

21) What happens if you exceed the hourly publishing limit?
Events published beyond the limit will fail. Organizations must monitor and optimize their event publishing to stay within the allowed limits.

22) What is Change Data Capture (CDC)?
Change Data Capture is a streaming product in Salesforce that enables real-time integration with external systems. It notifies subscribed systems of data changes like record creation, updates, deletions, and undeletions, helping keep external systems in sync without periodic data exports or repeated API calls.

23) What types of objects support CDC?
CDC is available for all custom objects and a subset of standard objects. Each object has an associated ChangeEvent object, named ObjectNameChangeEvent for standard objects and ObjectName__ChangeEvent for custom objects.

24) Can CDC events be queried or modified?
No, ChangeEvent objects don’t support CRUD operations or queries. They are used to capture and publish changes but cannot be directly manipulated.

25) How does CDC handle security for fields in change events?
CDC respects field-level security, delivering only the fields a user has access to. However, it ignores record-level sharing settings and doesn’t include derived fields (e.g., formula fields) except for roll-up summary fields.

26) What is the RestRequest class in Salesforce, and what are some of its key methods?
The RestRequest class in Salesforce is used to access incoming requests in Apex REST web services. It provides several methods to handle different aspects of an HTTP request. Some key methods include:
headers: Returns the headers received by the request (Map<String, String>)
httpMethod: Returns the HTTP method used for the request (String), such as GET, POST, DELETE, etc.
params: Returns the parameters received by the request (Map<String, String>)
remoteAddress: Returns the IP address of the client making the request (String)
requestBody: Returns or sets the body of the request (Blob)
requestURI: Returns or sets everything after the host in the HTTP request string (String)
resourcePath: Returns the REST resource path for the request (String)

27) What is the RestResponse class in Salesforce, and what are some of its key methods?
The RestResponse class in Salesforce is used to pass data from an Apex RESTful web service method to the HTTP response. It has several key methods:
responseBody: Returns or sets the body of the response (Blob)
headers: Returns the headers to be sent in the response (Map<String, String>)
statusCode: Returns or sets the HTTP status code for the response (Integer). Common status codes include 200 (OK), 201 (Created), 400 (Bad Request), etc.
For example, if you want to change the default status code of a RESTful service response, you can modify the statusCode property of the RestResponse class, like setting it to 201 (Created) instead of 200 (OK).

28) What is the purpose of the @HttpGet annotation in Salesforce, and how is it used in Apex?
The @HttpGet annotation in Salesforce is used to expose an Apex method as a RESTful GET service. This annotation allows external systems to retrieve data from Salesforce by making an HTTP GET request to the defined URL. The method must be defined as global static within a class annotated with @RestResource. For example, a method annotated with @HttpGet can fetch records like an Account based on an ID provided in the request URL.

29) Can you explain how Salesforce handles multiple HTTP methods in a single Apex class, and what restriction exists regarding their usage?
In Salesforce, a single Apex class can expose multiple HTTP methods (GET, DELETE, POST, PUT, PATCH) through different annotated methods. However, each method can only be annotated with one of these HTTP methods—only one method per HTTP method type is allowed in a class. For example, you can have one method annotated with @HttpGet, another with @HttpPost, and so on, but you cannot have multiple methods using the same annotation (e.g., two @HttpGet methods in the same class). This ensures each HTTP action is uniquely handled by its corresponding method.

30) What are named credentials in Salesforce and how do they improve security when integrating with external services?
Named credentials in Salesforce provide a secure and declarative way to store and manage the authentication details (like usernames, passwords, or OAuth tokens) required for HTTP callouts to external systems. They allow developers to specify the endpoint URL and authentication parameters in one definition, simplifying the setup of authenticated callouts. Named credentials eliminate the need for remote site settings and ensure credentials are stored encrypted, enhancing security. They also make maintaining integrations easier—if an endpoint URL changes, only the named credential needs to be updated, and all related callouts remain functional without modifying the Apex codo.

Monday, July 21, 2025

Understanding WITH SECURITY_ENFORCED in Salesforce Apex

When writing Apex code in Salesforce, it’s important to protect data by checking user permissions like Field-Level Security (FLS) and Object-Level Security (OLS). One way to do this is by using WITH SECURITY_ENFORCED in your SOQL queries.

This keyword tells Salesforce to check if the current user has access to the fields and objects in the query. If the user doesn’t have access, the query fails and throws an error. This helps avoid showing data that the user shouldn’t see.

Account[] accts = [SELECT Name, AnnualRevenue FROM Account WITH SECURITY_ENFORCED];

In this example, Salesforce checks if the user can access the Name and AnnualRevenue fields. If not, it will stop the query and show an error.

Salesforce Recommendation: Use USER_MODE Instead

Salesforce recommends using WITH USER_MODE instead of WITH SECURITY_ENFORCED because it has fewer limitations and works better in more situations.

With USER_MODE, your Apex code runs as if it were the user, automatically respecting all their permissions—without needing extra checks.

For more details on user mode please refer blog https://www.sfdc-lightning.com/2025/06/user-mode-in-apex-new-way-to-respect.html

Important Notes:

Don’t use WITH SECURITY_ENFORCED and USER_MODE together in the same query.

If you switch to USER_MODE, remove any WITH SECURITY_ENFORCED clauses—they’re not needed.

Using both together will cause errors.

Limitations of WITH SECURITY_ENFORCED:

  • Works only with SOQL

WITH SECURITY_ENFORCED works only in SOQL queries. It cannot be used with SOSL or DML.

Valid Example:

Account[] accs = [SELECT Name FROM Account WITH SECURITY_ENFORCED];

  • Does not support relationship fields

You cannot use relationship fields like Owner.Name in the query.

Invalid Example:

[SELECT Name, Owner.Name FROM Account WITH SECURITY_ENFORCED];

  • Cannot be used in dynamic SOQL

WITH SECURITY_ENFORCED does not work in queries written as strings and executed at runtime.

Invalid Example:

String soql = 'SELECT Name FROM Account WITH SECURITY_ENFORCED';

Database.query(soql); // This will fail

  • Exceptions cannot be caught

If the user doesn’t have access to a field or object, the query throws an exception that cannot be handled with try-catch.

Invalid Example:

try {

    [SELECT Name, AnnualRevenue FROM Account WITH SECURITY_ENFORCED];

} catch (Exception e) {

    // This will not catch the error

}

  • No partial access allowed

If the user lacks access to even one field, the entire query fails. It does not return partial results.

Example:

[SELECT Name, AnnualRevenue FROM Account WITH SECURITY_ENFORCED];

Saturday, July 12, 2025

User Mode vs WITH SECURITY_ENFORCED in Apex


Feature / Aspect

User Mode

WITH SECURITY_ENFORCED

Purpose

Enforces user permissions (FLS & CRUD) automatically in SOQL and DML

Enforces FLS & CRUD in SOQL only

Scope

Works with SOQL, DML, Async Apex (Batch, Queueable, etc.)

Works only with SOQL

Syntax Example

Database.query(new Query("SELECT Name FROM Account").setUserMode(UserMode.CURRENT));

[SELECT Name FROM Account WITH SECURITY_ENFORCED];

Field-Level Security (FLS)

Respected automatically

Respected, but throws error if access is denied

Object-Level Security (CRUD)

Respected automatically

Respected, but throws error if access is denied

Partial Access Handling

Returns only accessible fields/objects

Fails completely if any field/object is restricted

Error Handling

No error thrown for restricted fields; they are silently excluded

Throws uncatchable exception if access is denied

Support for Relationship Fields

✅ Supported

❌ Not supported (e.g., Owner.Name fails)

Support in Dynamic SOQL

✅ Fully supported

❌ Not supported

Support in DML Operations

✅ Supported via Database.DMLOptions.setUserMode()

❌ Not supported

Async Apex Compatibility

✅ Works in Batch, Queueable, etc.

❌ Not supported

Ease of Use

Cleaner, safer, and more flexible

Requires careful handling and limited in scope

Salesforce Recommendation

✅ Recommended

❌ Not recommended anymore

Use Case Example

Secure insert: Database.insert(record, dmlOpts);

Secure query: [SELECT Name FROM Account WITH SECURITY_ENFORCED];

Limitations

Few limitations; more flexible

Many limitations (no dynamic SOQL, no DML, no async, no partial results)

Can Be Used Together?

❌ Cannot be combined with WITH SECURITY_ENFORCED

❌ Cannot be combined with UserMode

Understanding DescribeFieldResult in Apex with Real-Time Examples

In Salesforce Apex, the Schema.DescribeFieldResult class provides metadata about fields on standard and custom objects. This is especially useful when building dynamic applications that need to adapt to different field configurations or enforce field-level security.

To instantiate a DescribeFieldResult object, you can use the following syntax:

Schema.DescribeFieldResult dfr = Account.Description.getDescribe();

This retrieves metadata about the Description field on the Account object. Let’s explore some of the most useful methods available in DescribeFieldResult, with real-time examples for selected ones.

getPicklistValues()

Returns a list of active PicklistEntry objects for a picklist field.

Example:

Schema.DescribeFieldResult dfr = Account.Industry.getDescribe();

List<Schema.PicklistEntry> picklistValues = dfr.getPicklistValues();

for (Schema.PicklistEntry entry : picklistValues) {

    System.debug('Picklist Value: ' + entry.getLabel());

}

getSObjectType()

Returns the object type from which the field originates.

Example:

Schema.DescribeFieldResult dfr = Account.Name.getDescribe();

Schema.SObjectType objType = dfr.getSObjectType();

System.debug('Object Type: ' + objType.getDescribe().getName());

isAccessible()

Checks if the current user has visibility to the field.

Example:

Schema.DescribeFieldResult dfr = Contact.Email.getDescribe();

if (dfr.isAccessible()) {

    System.debug('User can access the Email field.');

} else {

    System.debug('User cannot access the Email field.');

}

isUpdateable()

Checks if the field can be edited by the current user.

Example:

Schema.DescribeFieldResult dfr = Opportunity.StageName.getDescribe();

if (dfr.isUpdateable()) {

    System.debug('User can update the StageName field.');

} else {

    System.debug('User cannot update the StageName field.');

}

Conclusion:

Using DescribeFieldResult methods allows developers to build smarter, more secure, and dynamic applications in Salesforce. Whether you're validating permissions, fetching picklist values, or inspecting field metadata, these tools are essential for robust Apex development.