Interview

10 Salesforce REST API Interview Questions and Answers

Prepare for your next interview with this guide on Salesforce REST API, featuring common questions and answers to enhance your technical skills.

Salesforce REST API is a powerful tool that allows developers to interact with Salesforce data using standard HTTP methods. It provides a simple and efficient way to access and manipulate Salesforce records, making it an essential skill for those working with Salesforce integrations. The API’s flexibility and ease of use have made it a popular choice for developers looking to build robust and scalable applications.

This article offers a curated selection of interview questions designed to test your knowledge and proficiency with the Salesforce REST API. By familiarizing yourself with these questions and their answers, you will be better prepared to demonstrate your expertise and problem-solving abilities in a technical interview setting.

Salesforce REST API Interview Questions and Answers

1. Describe the OAuth 2.0 flow used for authenticating with the Salesforce REST API.

OAuth 2.0 is an authorization framework that allows applications to obtain limited access to user accounts on an HTTP service. When authenticating with the Salesforce REST API, the OAuth 2.0 flow typically involves the following steps:

  • Authorization Request: The client application redirects the user to the Salesforce authorization server, requesting access to specific resources.
  • User Authentication: The user logs in to Salesforce and grants the requested permissions to the client application.
  • Authorization Response: Salesforce redirects the user back to the client application with an authorization code.
  • Token Request: The client application exchanges the authorization code for an access token by making a request to the Salesforce token endpoint.
  • Token Response: Salesforce returns an access token (and optionally a refresh token) to the client application.
  • API Requests: The client application uses the access token to make authenticated requests to the Salesforce REST API.

2. Write a sample cURL command to create a new Account record in Salesforce.

To create a new Account record in Salesforce using a cURL command, you need to include the appropriate headers for authorization and content type, as well as the data payload in JSON format.

Example:

curl https://yourInstance.salesforce.com/services/data/vXX.X/sobjects/Account/ \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"Name": "New Account Name", "Phone": "1234567890", "Website": "www.example.com"}'

In this example:

  • Replace yourInstance with your Salesforce instance (e.g., na1, eu1).
  • Replace XX.X with the API version you are using (e.g., v52.0).
  • Replace YOUR_ACCESS_TOKEN with your actual Salesforce access token.
  • The data payload includes fields such as Name, Phone, and Website for the new Account record.

3. What are some common HTTP status codes returned by the Salesforce REST API, and what do they mean?

Common HTTP status codes returned by the Salesforce REST API include:

  • 200 OK: The request was successful, and the server returned the requested data.
  • 201 Created: The request was successful, and a new resource was created as a result.
  • 204 No Content: The request was successful, but there is no content to send in the response.
  • 400 Bad Request: The server could not understand the request due to invalid syntax.
  • 401 Unauthorized: The client must authenticate itself to get the requested response.
  • 403 Forbidden: The client does not have access rights to the content.
  • 404 Not Found: The server can not find the requested resource.
  • 500 Internal Server Error: The server has encountered a situation it doesn’t know how to handle.

4. Write an Apex class that exposes a custom REST endpoint to create a new Lead record.

To create a custom REST endpoint in Salesforce using Apex, you need to define an Apex class with the appropriate annotations. The @RestResource annotation is used to define the endpoint, and the @HttpPost annotation is used to handle POST requests. Below is an example of how to implement this:

@RestResource(urlMapping='/createLead')
global with sharing class LeadService {
    @HttpPost
    global static String createLead(String lastName, String company) {
        Lead newLead = new Lead(LastName = lastName, Company = company);
        try {
            insert newLead;
            return 'Lead created with Id: ' + newLead.Id;
        } catch (DmlException e) {
            return 'Error: ' + e.getMessage();
        }
    }
}

5. How would you debug a failed API call in Salesforce? What tools or methods would you use?

To debug a failed API call in Salesforce, you can use several tools and methods to identify and resolve the issue. Here are some key steps and tools you can use:

  • Check the API Response: Examine the response from the API call for error codes and messages that can provide insights into what went wrong.
  • Salesforce Debug Logs: Enable debug logs in Salesforce to capture detailed information about the API call. You can set up debug logs for specific users or processes to get a granular view of what is happening during the API call.
  • Workbench: Salesforce Workbench is a powerful tool that allows you to interact with Salesforce APIs. You can use Workbench to make API calls and inspect the responses. It also provides a way to view debug logs and other diagnostic information.
  • Postman: Postman is a popular tool for testing APIs. You can use Postman to replicate the API call and inspect the request and response. This can help you identify issues with the request format, headers, or authentication.
  • Check API Limits: Ensure that you have not exceeded any API limits set by Salesforce. Exceeding limits can result in failed API calls. You can monitor your API usage in Salesforce to ensure you are within the allowed limits.
  • Review Code and Configuration: If the API call is made from custom code or a third-party application, review the code and configuration to ensure it is correct. Look for issues such as incorrect endpoints, missing parameters, or authentication problems.
  • Salesforce Status and Known Issues: Check the Salesforce status page and known issues to see if there are any ongoing issues that could be affecting your API calls.

6. Provide an example of a complex integration scenario involving the Salesforce REST API and explain how you would implement it.

A complex integration scenario involving the Salesforce REST API could be integrating Salesforce with an external e-commerce platform to synchronize customer data and order information. This integration would involve several steps, including authentication, data retrieval, data transformation, and data update.

  • Authentication: Use OAuth 2.0 to authenticate and obtain an access token for the Salesforce API.
  • Data Retrieval: Retrieve customer and order data from the e-commerce platform using its API.
  • Data Transformation: Transform the retrieved data to match the Salesforce data model.
  • Data Update: Use the Salesforce REST API to update or create records in Salesforce.

Example:

import requests

# Step 1: Authentication
def get_access_token(client_id, client_secret, username, password):
    auth_url = 'https://login.salesforce.com/services/oauth2/token'
    payload = {
        'grant_type': 'password',
        'client_id': client_id,
        'client_secret': client_secret,
        'username': username,
        'password': password
    }
    response = requests.post(auth_url, data=payload)
    return response.json().get('access_token')

# Step 2: Data Retrieval
def get_ecommerce_data(api_url, headers):
    response = requests.get(api_url, headers=headers)
    return response.json()

# Step 3: Data Transformation
def transform_data(ecommerce_data):
    transformed_data = []
    for record in ecommerce_data:
        transformed_data.append({
            'FirstName': record['first_name'],
            'LastName': record['last_name'],
            'Email': record['email'],
            'OrderAmount': record['order_amount']
        })
    return transformed_data

# Step 4: Data Update
def update_salesforce_data(access_token, salesforce_url, data):
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    for record in data:
        response = requests.post(salesforce_url, headers=headers, json=record)
        print(response.status_code, response.json())

# Example usage
client_id = 'your_client_id'
client_secret = 'your_client_secret'
username = 'your_username'
password = 'your_password'
access_token = get_access_token(client_id, client_secret, username, password)

ecommerce_api_url = 'https://api.ecommerce.com/customers'
ecommerce_headers = {'Authorization': 'Bearer your_ecommerce_token'}
ecommerce_data = get_ecommerce_data(ecommerce_api_url, ecommerce_headers)

transformed_data = transform_data(ecommerce_data)

salesforce_url = 'https://your_instance.salesforce.com/services/data/vXX.X/sobjects/Contact'
update_salesforce_data(access_token, salesforce_url, transformed_data)

7. Describe how to handle error responses from the Salesforce REST API.

When working with the Salesforce REST API, error responses typically come with an HTTP status code and a JSON response body that contains details about the error. Common HTTP status codes include 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), and 500 (Internal Server Error). The JSON response body usually contains fields like errorCode and message that provide more context about the error.

To handle these error responses effectively, you can implement error handling logic in your code to check the HTTP status code and parse the JSON response body for error details. This allows you to take appropriate actions, such as retrying the request, logging the error, or displaying a user-friendly message.

Example:

import requests

def make_salesforce_request(url, headers):
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        error_info = response.json()
        error_code = error_info.get('errorCode')
        error_message = error_info.get('message')
        handle_error(response.status_code, error_code, error_message)

def handle_error(status_code, error_code, error_message):
    print(f"Error {status_code}: {error_code} - {error_message}")
    # Add additional error handling logic here

# Example usage
url = "https://your-instance.salesforce.com/services/data/v52.0/sobjects/Account"
headers = {
    "Authorization": "Bearer your_access_token",
    "Content-Type": "application/json"
}

make_salesforce_request(url, headers)

8. Explain the JWT Bearer Token Flow for authentication with the Salesforce REST API.

The JWT Bearer Token Flow for authentication with the Salesforce REST API involves several key steps:

  • Create a JWT (JSON Web Token): The JWT is a compact, URL-safe token that includes a header, payload, and signature. The payload contains claims such as the issuer (client ID), subject (user), audience (Salesforce), and expiration time.
  • Sign the JWT: The JWT is signed using the private key of the connected app’s certificate. This ensures the integrity and authenticity of the token.
  • Request an Access Token: The signed JWT is sent to the Salesforce token endpoint. Salesforce verifies the signature using the public key of the connected app’s certificate and, if valid, issues an access token.
  • Use the Access Token: The access token is then used to authenticate API requests to Salesforce.

Example of JWT payload:

{
  "iss": "client_id",
  "sub": "[email protected]",
  "aud": "https://login.salesforce.com",
  "exp": 1516239022
}

9. How would you use the Composite API to update multiple records in a single request? Provide an example.

The Salesforce Composite API is designed to handle multiple operations in a single request, which can be particularly useful for reducing the number of API calls and improving performance. This is achieved by combining several sub-requests into a single composite request. Each sub-request can be a different type of operation, such as creating, updating, or deleting records.

To update multiple records in a single request using the Composite API, you would typically use the composite resource. This allows you to bundle multiple PATCH requests into one. Each sub-request is executed in the order it is specified, and the entire composite request is treated as a single transaction.

Example:

{
  "compositeRequest": [
    {
      "method": "PATCH",
      "url": "/services/data/v52.0/sobjects/Account/001D000000IqhSLIAZ",
      "referenceId": "RefAccount1",
      "body": {
        "Name": "Updated Account Name 1"
      }
    },
    {
      "method": "PATCH",
      "url": "/services/data/v52.0/sobjects/Account/001D000000IqhSMIAZ",
      "referenceId": "RefAccount2",
      "body": {
        "Name": "Updated Account Name 2"
      }
    }
  ]
}

In this example, two PATCH requests are bundled into a single composite request. Each sub-request updates a different Account record with a new name. The referenceId is used to uniquely identify each sub-request within the composite request.

10. Describe a real-time integration scenario using the Salesforce REST API and how you would implement it.

Real-time integration involves the immediate transfer of data between systems as soon as an event occurs. In the context of Salesforce, this can be achieved using the Salesforce REST API to communicate with external systems.

A common scenario is integrating Salesforce with an external order management system. When a new order is created in the external system, it should be immediately reflected in Salesforce.

To implement this, you would:

  • Set up a connected app in Salesforce to obtain the necessary OAuth tokens for authentication.
  • Use the external system to make HTTP POST requests to the Salesforce REST API endpoint to create or update records in real-time.

Example:

import requests

def create_salesforce_order(order_data):
    access_token = 'YOUR_ACCESS_TOKEN'
    instance_url = 'https://yourInstance.salesforce.com'
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    url = f'{instance_url}/services/data/v52.0/sobjects/Order'
    response = requests.post(url, headers=headers, json=order_data)
    return response.json()

order_data = {
    'AccountId': '001xx000003DGbYAAW',
    'EffectiveDate': '2023-10-01',
    'Status': 'Draft'
}

create_salesforce_order(order_data)
Previous

10 Google Data Studio Interview Questions and Answers

Back to Interview
Next

10 HashSet Interview Questions and Answers