Showing posts with label Integrations. Show all posts
Showing posts with label Integrations. Show all posts

Monday, June 26, 2023

Composite Batch- Way to call multiple REST API in single request (sending multiple request to Salesforce)

Composite batch allows to send up to 25 separate API request in a single call to salesforce. Best thing about this is that all sub-request are considered as separate call. Suppose you want to move multiple records to next salesforce org or want to create multiple records in salesforce from external system then this will help you.


By using composite batch API, I am going to create a new Account record, Update existing Account record (by using external Id field -Account_Unique_Id__c) and query account record in same API call.

Below are details you need:

REST API service URI-   /services/data/v56.0/composite/batch/

Request Body Sample-

{

"batchRequests": [{

"method": "POST",

"url": "v56.0/sobjects/Account",

"richInput": {

"Name": "New Account using Composite Batch"

}

},

{

"method": "PATCH",

"url": "v56.0/sobjects/account/Account_Unique_Id__c/ACC-000033",

"richInput": {

"NumberOfEmployees": "2000",

"Type": "Customer"

}

}, {

"method": "GET",

"url": "v56.0/query/?q=SELECT+name+from+Account+where+Account_Unique_Id__c='ACC-000033'"

}

]

}


Response Body:

{

"hasErrors": false,

"results": [{

"statusCode": 201,

"result": {

"id": "0010K00002mziKJQAY",

"success": true,

"errors": []

}

}, {

"statusCode": 200,

"result": {

"id": "0010K00002PBQTyQAP",

"success": true,

"errors": [],

"created": false

}

}, {

"statusCode": 200,

"result": {

"totalSize": 1,

"done": true,

"records": [{

"attributes": {

"type": "Account",

"url": "/services/data/v56.0/sobjects/Account/0010K00002PBQTyQAP"

},

"Name": "Sunil Test Account"

}]

}

}]

}


Important points to consider while using this:

  • The response bodies and HTTP statuses of the subrequests in the batch are returned in a single response body.
  • Each sub request counts against rate limits.
  • Each API request are considered as separate and you can not pass information between them.
  • If one API request get successfully completed from batch request, then it gets committed. If any subsequent request fails then previous request is not rollbacked automatically.
  • Batch request should complete in 10 minutes. If batch times out then the remaining sub requests aren’t executed

Hope this will help!!



Friday, April 17, 2020

Get the Content (Blob) of File from Box and Store/Manipulate it in Salesforce

Through this blog, I am going to share sample apex script through which you can get content of file from box as blob and then store or manipulate it within salesforce.

I have already written a blog to explain how to get box access token (needed for handshake with Box) and to display file content in salesforce in VF page without storing it in salesforce. You can cosider it as Mashup inSalesforce. Please refer below URL to that:

Box and Salesforce Integration

In order to get box file content, we need to have box file Id and box access token.

Box does not provide direct API to get file content. First you need to do callout to get download URL and then you perform another API callout to get file content. Also you perform another API call to get file details like filename in order to store it in salesforce.

I am going to store box file in salesforce library for demo purpose. You can store it as attachments or read the content on the fly to perform some logic instead of saving it.

Add below URLs in remote site settings before performing the callouts:
  • https://api.box.com
  • https://dl.boxcloud.com 

Below is required code and it is self explainatory as comments are mentioned for each methods:

Now run below script in developer console:

string boxFileId='6542xxx28604';
string access_token='0xxxxxxxxxxxxxxxxxxxxxxxxxxxredx0P';
string sfdcLibraryName='Box_File_Library';
string boxFilename= SK_BoxAPIUtilityClass.findFileNameFromBox(boxFileId,access_token);
system.debug('****boxFilename:'+boxFilename);
SK_BoxAPIUtilityClass.readFileContentFromBox(boxFileId,boxFilename,sfdcLibraryName,access_token);



Use Case

During sandbox refresh, all custom settings data gets refreshed from production values. So before refresh, you have to take back up each custom settings data and after refresh, you need to update the custom setting records. In order to automate this, you can write script through which you can push all custom setting data to box folder. Code to upload the files from Salesforce to box is already shared in blog  Box and Salesforce Integration.

Now we need to get the content of all csv files stored in box and update the custom setting in salesforce. Once you get the content of file, you can parse csv file and update custom settings.

Hope this helps!!!


Saturday, November 2, 2019

Migrate Attachments from one Salesforce to another Salesforce Org

Through this blog, I will be sharing simple apex code through which you can fetch the attachment from another org and save it in your current org as attachments. This process includes 2 API calls as mentioned below:
  • First API call to fetch attachment details like attachment name etc.
  • Second API call to fetch attachment body.  Attachment body will be returned in binary format so get the response body as blob and then use it to insert attachment in your current org.

Below is code snippet which you can use to migrate attachment:


In order to test above script, run below mentioned script in developer console:

string sourceOrgUrlAttachmentId='00P0K00001ZvWpe';
string sourceOrgURL='https://sk02-dev-ed.my.salesforce.com';
string access_Token='0XXXXXXXXXXXXXXXXXX8ADac';
string currOrgParentRecid='00190000004Awot';
string result=SK_AttachmentMigrationHelper.findAttachmentDetails(sourceOrgUrlAttachmentId,sourceOrgURL,access_Token,currOrgParentRecid);
system.debug('***attachment Id after migration:'+result);

Instead of access_token, you can also use sessiond of user from source Org.

Refer below URL to understand how to get access token from salesforce:

ACCESS TOKEN USING OAUTH 2.0 IN SALESFORCE


How to get all attachments related to parent record Id

Specify endpoint URL as mentioned below while performing callout:

string parentRecId='001xxxxxxxxxxx';
EndPointURL= EndPointURL +'/services/data/v45.0/query/?q=select+id,parentid,ContentType,+name+from+attachment+where+parentid=\''+parentRecId+'\'';


How to migrate bulk attachments from one salesforce org to another

Before migrating the attachments, you will be migrating the parent records from source org to target org. So while migrating store the source org record Id in new custom field in target org.

Now write a batch class in target org and take references from above code to process records one by one. Execute the batch class with 1 batch size.

Hope this will help!!

Monday, September 23, 2019

Box API : How to Regenerate Access Token from Refresh Token

Box and Salesforce can be integrated to store files on box and link them with salesforce records. You can also write apex script to extract files or attachments from Salesforce and upload it into box folder.

For basic understanding on how to generate access token from box, refer below URL:
Box and Salesforce Integration

Whenever we perform handshake with box using OAuth, box returns access token along with refresh token. Below is sample JSON response for access token:

{
"access_token": "h91xxxxxxxxxxxxxxxxxxxx8",
"expires_in": 4012,
"restricted_to": [],
"refresh_token": "bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxM",
"token_type": "bearer"
}

here expires_in specifies the duration for which this access token is valid. After this duration, user will recieve 401 error so we need to regenerate the access token using refresh token.

Below is apex code which can be used to regenerate new access token and refresh token. In order to regenerate you need clientid, client secret and refresh token.

Above mentioned code is self explainatory.


Hope this help!!!


Saturday, November 24, 2018

Integration Patterns and Best Practices for Salesforce - Part 2

This is my second blog to explain Integration patterns and best practices.  In this I will cover remaining patterns.

In order to understand the patterns covered in previous blog, refer below link:
Integration Patterns and Best Practices for Salesforce - Part 1

If you are planning to appear for "SALESFORCE CERTIFIED INTEGRATION ARCHITECTURE DESIGNER" exam then below information will be helpful.

Note: I have summarized the information provided in Integration Patterns and Practices documentation provided by salesforce in this blog.

Batch Data Synchronization

Use this pattern if you want to import data into Salesforce and export data out of Salesforce, taking into consideration that these imports and exports can interfere with end-user operations during business hours, and involve large amounts of data.
Below are different scenarions which can utilize this pattern:
  • Extract and transform accounts, contacts, and opportunities from the current CRM system and load the data into Salesforce (initial  data import).
  • Extract, transform, and load customer billing data into Salesforce from a remote system on a weekly basis (ongoing).
  • Extract customer activity information from Salesforce and import it into an on-premises data warehouse on a weekly basis (ongoing backup).      
Change data capture    
  • If remote system is master
Leverage a third-party ETL tool that allows you to run change data capture against source data. The tool reacts to changes in the source data set, transforms the data, and then calls Salesforce Bulk API to issue DML statements. This can also be implemented using the Salesforce SOAP API.  
  • If Salesforce system is master
If Salesforce is the data source then you can use time/status information on individual rows to query the data and  filter the target result set. This can be implemented by using SOQL together with SOAP API and the query() method, or by the using SOAP API and the getUpdated() method.

In case of using middleware, it is recommend that you create the control tables and associated data structures in an environment that the ETL tool has access. This provides adequate levels of resilience. Salesforce should be treated as a spoke in this process and the ETL infrastructure is the hub.
For an ETL tool to gain maximum benefit from data synchronization capabilities, consider the following:
  • Chain and sequence the ETL jobs to provide a cohesive process.
  • Use primary keys from both systems to match incoming data.
  • Use specific API methods to extract only updated data.
  • If importing child records in a master-detail or lookup relationship, group the imported data using its parent key at the source to avoid locking. For example, if you’re importing contact data, be sure to group the contact data by the parent account key so that maximum number of contacts for a single account can be loaded in one API call. Failure to group the imported data usually results in the first contact record being loaded and subsequent contact records for that account to fail in the context of the API call.
  •  Any post-import processing, such as triggers, should only process data selectively.
Error Handling and Recovery
  • Exporting data from SFDC
During read operation from salesforce, middleware should perform below operations
  • Log the error
  • Retry the read operation
  • Terminate if unsuccessful
  • Send a notification
  • Importing data into SFDC
Handling—Errors that occur during a write operation via middleware can result from a combination of factors in the application (record locking errors). The API calls return a result set that consists of the information listed below. This information should be used to retry the write operation (if necessary).
  • Record identifying information
  • Success/failure notification
  • collection of errors for each record
Security Considerations
  • A Lightning Platform license is required to allow authenticated API access to the Salesforce API.
  • It is recommended to use standard encryption to keep password access secure.
  • Use the HTTPS protocol when making calls to the Salesforce APIs. You can also proxy traffic to the Salesforce APIs through an on-premises security solution, if necessary.
Timeliness

Timeline is not significant factor as these operations runs in background. Loading batches during business hours might result in some contention, resulting in either a user's update failing, or more significantly, a batch load (or partial batch load) failing.
For organizations that have global operations, it might not be feasible to run all batch processes at the same time because the system might continually be in use. Data segmentation techniques using record types and other filtering criteria can be used to avoid data contention in these cases.

Data Volumes

This pattern is mainly used for bulk data import and export.

Remote Call-In


This pattern is used when remote system wants to connect to salesforce and after authentication, want to update records in SFDC.
Below are different options available for this:
  • SOAP API
Query, Create update or delete records and obtain metadata information from Salesforce
Salesforce provides two WSDLs for remote systems:
  • Enterprise WSDL—Provides a strongly-typed WSDL that’s specific to a Salesforce organization.
  • Partner WSDL—Contains a loosely-typed WSDL that’s not specific to a Salesforce organization. It deals with considering subject structure.
Security :- The client executing SOAP API must have a valid login and obtain a session to perform any API calls. The API respects object-level and field-level security configured in the application based on the logged in user’s profile.
Data Volume :- For bulk data operations (more than 500,000 records), use the REST-based Bulk API.
  • REST API
Query, Create update or delete records and obtain metadata information from Salesforce
REST exposes resources (entities/objects) as URIs and uses HTTP verbs to define CRUD perations on these resources. Unlike SOAP, the REST API requires no predefined contract, utilizes XML and JSON for responses, and has loose typing. REST API is lightweight and provides a simple method for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice for use with mobile applications and Web 2.0 projects.
Security:-  We recommend that the remote system establish an OAuth trust for authorization.  It’s also possible to make REST calls with a valid session ID that might have been obtained by other means (for example, retrieved by calling SOAP API or provided via an outbound message).
We recommend that clients that call the REST API cache and reuse the session ID to maximize performance, rather than obtaining a new session ID for each call.
  • Custom Webservices/Apex Rest classes
We can create custom webservices and provide WSDL to remote system so that they can consume it and call custom webservices methods. If we create Apex rest services, then remote system can directly call URI’s.
Custom webservices or Apex Rest services are usefull when you need to update multiple records related to different objects in single call as logic for complete transaction is controlled by developer.
  • Bulk API
Bulk API is based on REST principles, and is optimized for loading or deleting large sets of data. It has the same accessibility and security behavior as REST API.
Bulk API allows the client application to query, insert, update, upsert, or delete a large number of records asynchronously by submitting a number of batches, which are processed in the background by Salesforce. In contrast, SOAP API is optimized for real-time client applications that update small numbers of records at a time.
Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands to millions of records, it becomes less practical. This is due to its relatively high overhead and lower performance characteristics.

Error Handling and Recovery

Error handling needs to be implemented by remote system or middleware. Middleware or remote system should implement retry logic and also need to make sure that duplicate request is coming to salesforce. We can handle duplicate request in case of custom webservices or apex rest services but it is required for remote system to have some mechanism for this.

Timelines

SOAP and REST API’s are synchronous.

Data Volume

SOAP/REST API
  • Login—The login request size is limited to 10 KB or less.
  • Create, Update, Delete—The remote system can create, update, or delete up to 200 records at a time. Multiple calls can be made to process more than a total of 200 records, but each request is limited to 200 records in size.
  • Query Results Size — By default, the number of rows returned in the query result object (batch size), returned in a query() or queryMore() call is set to 500. Where the number of rows to be returned exceeds the batch size, use the queryMore() API call to iterate through multiple batches. The maximum batch size is 2,000 records
BULK API
Bulk API is synchronous when submitting the batch request and associated data. The actual processing of the data occurs asynchronously in the background.
  • Up to 2,000 batches can be submitted per rolling 24–hour period.
  • A batch can contain a maximum of 10,000 records.


UI Update Based on Data Changes


When an event occurs in Salesforce like update to any record, user should be notified in the Salesforce user interface without having to refresh their screen and potentially losing work.
The recommended solution to this integration problem is to use the Salesforce Streaming API.
This solution is comprised of the following  components:
  • A PushTopic with a query definition that allows you to:
    • Specify what events trigger an update
    • Select what data to include in the notification
  • A JavaScript-based implementation of the Bayeux protocol (currently CometD) that can be used by the user interface
  • A Visualforce page
  • A JavaScript library included as a static resource
Benefit of Streaming API
  • No need to write pooling mechanism to identify the records changes
  • User does not have to refresh record or invoke any action to get latest updates
    Limitations
    • Delivery of notifications isn’t guaranteed.
    • Order of notifications isn’t guaranteed.
    • Notifications aren’t generated from record changes made by Bulk API.
      Security Considerations

      It respect Salesforce organization-level security.

      Idempotent Design Considerations
      • Remote Process Invocation—Request and Reply / Request and Forget
      It’s important to ensure that the remote procedure being called is idempotent means it can identify if any repeated request is coming to avoid duplicates request processing. It’s almost impossible to guarantee that Salesforce only calls once, especially if the call is triggered from a user interface event. Even if Salesforce makes a single call, there’s no guarantee that other processes (for example, middleware) do the same.
      The most typical method of building an idempotent receiver is for it to track duplicates based on unique message identifiers sent by the consumer. Apex web service or REST calls must be customized to send a unique message ID.
      • Remote Call In
      The remote system must manage multiple (duplicate) calls, in the case of errors or timeouts, to avoid duplicate inserts and redundant updates (especially if downstream triggers and workflow rules fire). While it’s possible to manage some of these situations within Salesforce (particularly in the case of custom SOAP and REST services), we recommend that the remote system (or middleware) manages error handling and idempotent design.



      Hope this will help!!

      Friday, November 23, 2018

      Integration Patterns and Best Practices for Salesforce - Part 1

      Whenever you have to integrate Salesforce with remote system, then you need to consider different integration scenarios and API’s availability. Integration patterns helps you identify the correct pattern or API to build robust framework for integration.

      If you are planning to appear for "SALESFORCE CERTIFIED INTEGRATION ARCHITECTURE DESIGNER" exam then below information will be helpful.

      In complex integration scenarios, mix of integration patterns is used by weighing pros and cons accordingly.

      Today I am going to cover below patterns. For remaining patterns, refer below blog:
      Integration Patterns and Best Practices for Salesforce - Part 2

      Remote Process Invocation—Request and Reply


      This pattern is used when you need to call remote system and wait for response. After getting response you want to update something in SFDC in synchronous manner. This pattern is used when you want to complete request and process the response in same transaction.

      Different Scenarios:
      • Onclick of button in UI :- In VF page, onclick of button you want to call remote system to get order information and display it to user on VF page without storing it in salesforce. You can implement this with Apex SOAP or REST callouts.
      • Apex triggers :-You can use Apex triggers to perform callouts based on record data changes. All calls made from within the trigger context must execute asynchronously from the initiating event. Therefore, apex triggers isn’t recommended for this pattern.
      • Batch Class :- You can make calls to a remote system from a batch job. This solution allows batch remote process execution and processing of the response from the remote system in Salesforce. However, a given batch has limits to the number of calls. So, batch class is also not recommended for this pattern.
      Error Handling and Recovery

      It’s important to include an error handling and recovery strategy as part of the overall solution.
      • Error handling—When an error occurs (exceptions or error codes are returned to the caller), the caller manages error handling. For example, an error message displayed on the end-user’s page or logged to a table requiring further action.
      • Recovery—Changes aren’t committed to Salesforce until the caller receives a successful response. For example, the order status isn’t updated in the database until a response that indicates success is received. If necessary, the caller can retry the operation.
      Security Considerations

      Any call to a remote system must maintain the confidentiality, integrity, and availability of the request. The following security considerations are specific to using Apex SOAP and HTTP calls in this pattern.
      • One-way SSL is enabled by default (for apex callout and outbound messages), but two-way SSL is supported with both self-signed and CA-signed certificates to maintain authenticity of both the client and server.
      • Salesforce does not currently support WS-Security.
      • Where necessary, consider using one-way hashes or digital signatures using the Apex Crypto class methods to ensure request integrity.
      • The remote system must be protected by implementing the appropriate firewall mechanisms.
      Timeliness

      Timeliness is of significant importance in this pattern. Usually:
      • The request is typically invoked from the user interface, so the process must not keep the user waiting.
      • Salesforce has a configurable timeout of up to 60 seconds for calls from Apex.
      • Completion of the remote process is executed in a timely manner to conclude within the Salesforce timeout limit and within user expectations.
      Data Volumes

      This pattern is used primarily for small volume, real-time activities, due to the small timeout values and maximum size of the request or response for the Apex call solution. Do not use this pattern in batch processing activities in which the data payload is contained in the message.

      Remote Process Invocation—Fire and Forget

      This pattern is utilized when you want to send some information to remote system and don’t want wait for response. Consider the scenario in which order is created in salesforce and then order information is send to order fulfillment system (outside salesforce) which will process the order.
      Best example for this pattern utilization is Outbound messages.

      Different Scenarios:
      • Outbound messages and call back
      No customization is required in Salesforce to implement outbound messaging. The recommended solution for this type Workflow-driven outbound messaging Good of integration is when the remote process is invoked from an insert or update event. Salesforce provides a workflow-driven outbound messaging capability that allows sending SOAP messages to remote systems triggered by an insert or update operation in Salesforce. These messages are sent asynchronously and are independent of the Salesforce user interface. The outbound message is sent to a specific remote endpoint. The remote service must be able to participate in a contract-first integration where Salesforce provides the contract. On receipt of the message, if the remote service doesn’t respond with a positive acknowledgment, Salesforce retries sending the message, providing a form of guaranteed delivery.

      A single outbound message can send data only for a single object. A callback can be used to retrieve data from other related records, such as related lists associated with the parent object. The outbound message provides a unique SessionId that you can use as an authentication token to authenticate and authorize a callback with either the SOAP API or the REST API. The system performing the callback isn’t required to separately authenticate to Salesforce. The standard methods of either API can then be used to perform the desired business functions. A typical use of this variant is the scenario in which Salesforce sends an outbound message to a remote system to create a record. The callback updates the original Salesforce record with the unique key of the record created in the remote system.

      This is best use case for this pattern as information will be send from salesforce using outbound message without any customization. If other system is unavailable then, outbound has in-built retry mechanism for 24 hours.

      Also we can pass session id of user so that remote system can perform callback to SFDC to update records providing confirmation that request have been successfully received by remote system.

      Given the static, declarative nature of the outbound message, no complex integration such as aggregation, orchestration, or transformation, can be performed in Salesforce. The remotesystem or middleware must handle these types of operations .
      • VF and custom controllers
      You can utilize VF page and controllers to send information to remote system but it involves customization to grantee delivery of messages as remote system can be have downtime when request is send.
      • Apex triggers/Batch Class
      You can use Apex triggers to perform callouts based on record data changes. All calls made from within the trigger context must execute asynchronously from the initiating event. Batch and triggers also have API call limits

      Error Handling and Recovery

      An error handling and recovery strategy must be considered as part of the overall solution. The best method depends on the solution you choose.
      • Apex Callout – We need to maintain logic for retry and error handling if we didn’t get acknowledgement from remote or gets timeout error. Recovery mechanism is complex in this scenario
      • Outbound messages – Outbound has inbuilt retry mechanism.

      Security Considerations

      A call to a remote system must maintain the confidentiality, integrity, and availability of the request.For Outbound message, Whitelist Salesforce server IP ranges for remote integration servers as all Outbound messages are delivered from Salesforce IP addresses.

      Timeliness

      Timeliness is less of a factor with the fire-and-forget pattern. Control is handed back to the client either immediately or after positive acknowledgment of a successful hand-off in the remote system. With Salesforce outbound messaging, the acknowledgment must occur within 24 hours; otherwise, the message expires.

      Data Volumes

      Data volume considerations depend on which solution you choose. There is no limit on number of outbound messages sent but limits are there for apex callouts.

      Note:- I have summarized the information provided in Integration Patterns and Practices documentation provided by salesforce in this blog.

      Hope this will help!!!

      Monday, June 18, 2018

      Search Content on Box from Salesforce Using Content Search API

      In this blog, I am going to share the code snippet which can be used to do callout from Apex in order to search content on Box. You need to have access token in order to perform this callout.

      To learn how to get access token from box, please refer Box and Salesforce Integration

      Box provide content search API through which you can search for files and folders present in Box.
      I have created a wrapper class in apex which will be used to parse the JSON response from Box.

      Below is code snippet:

      You can call this static method and pass the parameters to get results.

      Hope this will help!!

      Wednesday, August 16, 2017

      Creating Apex Rest Services and Testing it with POSTMAN

      In this post, I am going to explain how to validate Apex Rest Service created in SFDC using POSTMAN (google chrome plugin).

      First we will create a very basic Apex Rest Service.


      After creating this class, now we can access this API by using below endpoint URL:

      https://xxxx.salesforce.com/services/apexrest/RestAPIDemo
      where xxxx is your domain URL or say instance URL like na15, cs30 etc.

      Here we have created Rest API which accepts GET & POST request.Whenever we will perform GET request, API will return Account records based on search string passed as parameter in endpoint URL.

      Now I will explain how to test this API Service by using POSTMAN.

      In order to invoke Apex REST API, we need to have access token. So first we will use Oauth 2.0 to get access token from SFDC in order to perform API calls.

      Steps to get access token from SFDC:

      • Create a connected App in SFDC.
      • Perform POST request from POSTMAN to below mentioned endPoint URL:

      https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=CLIENTID&client_secret=CLIENTSECRET&
      username=SFDCUSERNAME&password=SFDCPASSWORD_SECURITY_TOKEN

      Where 
             CLIENTID = consumer key from created connected app
             CLIENTSECRET= consumer secret from created connected app
             SFDCUSERNAME = SFDC username
             SFDCPASSWORD_SECURITY_TOKEN = password + security_token

      While performing POST request, specify header in which key will be "Content-Type" and value will be "application/x-www-form-urlencoded"



      You will recieve JSON response in which access_token will be specified. Copy and save it.

      Note:
      If you have enabled my domain then you can use domain URL as base URL in endpoint URL. If you are not using domain, then in JSON response you will get instance_URL which you can use base URL whenever you call APEX REST API's.


      How to perform GET request from POSTMAN to fetch data from SFDC
      • First create Endpoint URL(GET request).
                https:// BASE_URL/services/apexrest/RestAPIDemo?searchString=test
                where 
                BASE_URL is instance URL returned in JSON while requesting Access token.
                RestAPIDemo is REST Resource we specify while creating class.
                searchString : parameter passed to REST API which will return matched accounts
      • Specify Below headers
                [{"key":"Content-Type","value":"application/json"}]
                [{"key":"Authorization","value":"Authorization: Bearer Access_token"}]
      • Perform Get Request from POSTMAN


      How to perform POST request from POSTMAN to create new record

      • Create a JSON through which you send account information.
             {
        "accName":"SKtest By POSTMAN",
         "aType":"New Customer",
         "aIndustry":"IT"
              }   
      • Specify endpoint URL
             https://xxxx.salesforce.com/services/apexrest/RestAPIDemo
             where xxxx is domain of your org
      • Specify headers
                [{"key":"Content-Type","value":"application/json"}]
                [{"key":"Authorization","value":"Authorization: Bearer Access_token"}]
      • Send POST request through POSTMAN.

      Note:

      If your POST method contains parameter, then you have to pass JSON in different ways. For example POST method is:

      @HttpPost   
          global static String createNewAccount(accountWrapper accDetails) {
              string returnString='';
              try{
                  Account acc=new Account();
                  acc.Name= accDetails.accName;
                  acc.Type = accDetails.aType;
                  acc.Industry =accDetails.aIndustry;
                  insert acc;
                  returnString = 'Account created successfully with record Id:'+acc.id; 
              }catch(exception ex){
                  returnString = 'Request got failed: Error details-'+ex.getmessage();
              }
               return returnString;
          }

      In this scenario, JSON which needs to sent should be in below format:

      {
      "accDetails":{
      "accName":"SKtest By POSTMAN2",
      "aType":"New Customer",
      "aIndustry":"IT"
      }
      }

      Hope this will help!!!!

      More Blogs>>: 
      USING DATABASE.UPSERT WITH EXTERNAL ID   
      DYNAMIC APEX IN SALESFORCE   
      SOQL INJECTION IN SOQL   
      CUSTOM METADATA AND CUSTOM SETTINGS IMPLEMENTATION TRICKS   
      SMART TABLE USING ANGULARJS IN VISUALFORCE PAGE   
      REST API TUTORIAL FOR SALESFORCE   
      VISUALFORCE COMPONENT FOR RECORD STATUS BAR   
      DYNAMICALLY CREATING AND DESTROYING LIGHTNING COMPONENTS    
      RAISING AND HANDLING CUSTOM EVENTS IN sALESFORCE lIGHTNING    
      WHY TO USE DESIGN RESOURCE AND HOW TO ADD DYNAMIC OPTION TO DATASOURCE    
      PASSING INNER WRAPPER CLASS TO LIGHTNING COMPONENT    
      LIGHTNING COMPONENT FOR RECORDTYPE SELECTION FOR ANY SOBJECT    
      FETCHING FILE FROM EXTERNAL/PUBLIC URL AND STORING IT IN SALESFORCE   

      Saturday, February 25, 2017

      Fetching file from external/public URL and storing it into Salesforce

      If you have file URL for file stored outside the salesforce, then you can fetch file information from external URL by performing a call out to external system and store the file in salesforce.

      For Demo purpose, I have uploaded a pdf file in Google drive and shared it with link with people. Now I will fetch this file and will store it as attachment in salesforce under account record.

      File URL-  https://drive.google.com/file/d/0ByXILxflqQ2jWGpNVmI1WW9uYTQ/view?usp=sharing


      Below is apex class which will help us to perform this activity:



      Now you can run below code in developer console to test this:

      //you can specify any record Id where you want to store file as attachment
      String RecordId='0019000000ld4kN'; 
      String fileContentType='pdf';
      String extFileURL='https://drive.google.com/file/d/0ByXILxflqQ2jWGpNVmI1WW9uYTQ/view?usp=sharing';
      blob fileBlob=FileDownLoadUtility.fetchFileFromExternalUrl(extFileURL);
      Id attachmentId = FileDownLoadUtility.createAttachment(fileBlob, RecordId , fileContentType);
      system.debug('*****attachmentId:'+attachmentId);

      Note: 

      • If you are trying to fetch file from external source which is authenticated, then pass authorization parameters in HTTP Request headers
      • You should specify the file content type before creating attachment in order to properly view file.
      • You can add additional parameter as fileName in "createAttachment" method, if you you want specify the attachment name while creating attachment.

      While trying above code you may get below error:

      For this you need to add external URL in Remote Site Settings. For this example, I have added "https://drive.google.com/" in remote site settings.




      More Blogs>>: BOX AND SALESFORCE INTEGRATION    
      INTEGRATING BOX FILE PICKER WITH SALESFORCE
      REST API TUTORIAL FOR SALESFORCE




      Monday, February 20, 2017

      Integrating Box File Picker with Salesforce

      Box File Picker allows to view content present in box folders and to integrate it with other application. Suppose we want to display the box folder contents for user from salesforce UI, then we can use javascript code snippet provided for box file picker.

      Box File Picker allow your users to share their Box content with your application — without using OAuth!

      Now we are going to use below code sample to implement this in Salesforce. In order to use Box File Picker, you need Client Id or API Key.
      Navigate to your box application and click on Edit Application button.

      Suppose your URL is -https://app.box.com/developers/services/edit/133000

      Then Client Id is 133000




      Below is VF Page Code


      Explanation about different attributes in Box file picker:
      • linkType : The type of link. Can be direct or shared
        • shared : Allow you to select folder as well as file inside folder. Shared also allow you to specify the access type of file or folder like people with link, people in your company or people with access to folders
        • direct : Allow you to select only files not folder.
      • multiselect : true or false.
        • true: will get checkboxes for multiple file selection
        • false: will get radio button for single file selection

      Callback & Responses from Box File Picker

      Below javascript functions helps in integrating Box file picker with your application:

      // Register a success callback handler
      boxSelect.success(function(response) {
          console.log(response);
      });
      // Register a cancel callback handler
      boxSelect.cancel(function() {
          console.log("The user clicked cancel or closed the popup");
      });

      Details about callback functions:

      • Success function : Whenever user select files or folders, response is passed as JSON in sucess callback handler.
      • Cancel function : This function will be called whenever user click cancel or close the box file picker
      Below is sample JSON response which we will get in success callback function for shared link type:


      [
          {
              "url" : "https://app.box.com/s/jxi6hcwcvvbbccjka6k8ewhi3",
              "name" : "Happy Time",
              "access" : "collaborators",
              "type" : "folder",
              "id" : 100344004694
          },
          {
              "url" : "https://app.box.com/s/jdfaddssdc234232df123aad",
              "name" : "The Sunil Kumar.docx",
              "access" : "collaborators",
              "type" : "file",
              "id" : 1000000344
          }
      ]


      How to fetch files from Box and store it into salesforce

      You can pass the JSON to controller method using javascript remoting and parse JSON to find out file and folder information. JSON response return the file URL which can be used to get file details by doing callout and storing it as attachment in salesforce.

      Please refer Fetching File from External/Public URL for more details on this.



      BOX AND SALESFORCE INTEGRATION
      ACCESS TOKEN USING OAUTH 2.0 IN SALESFORCE
      REST API TUTORIAL FOR SALESFORCE

      Sunday, June 21, 2015

      Box and Salesforce Integration

      In this blog, I am going to explain how to integrate Box.com and Salesforce using Apex and VF in order to upload document to Box and to view files present in Box in VF page.

      First of all, Create a Box Application


      Create Box content application which will help us to upload files directly from Salesforce to Box.com.  After creating app, copy client_id and client_secret values and specify your VF page URL as redirect_uri in Oauth 2 parameters section.


      Now create another application and select Box view application. This will help us to view files in VF page. View API allow to convert files in HTML format for easy display in web pages. Copy view API Key from General information section.


      Now Create a custom setting in Salesforce to store client_id,client_secret, access token, refresh token and View API key.



      Now Create Remote site setting in order to do call out to Box.com.


      Now create a VF page "boxAuthPage" and apex class "boxAuthPageController". Code is provided in end of this blog. Please scroll down to copy code and paste in your VF and apex class.

      Snapshot of VF page:

      Store client_id, client_secret, view api key in custom setting record. While creating custom setting record, I have specified "Box_sunil02kumar' as name for custom setting. If you want to use other name, then replace "Box_sunil02kumar' in apex class with your custom setting name.

      Open VF page and click on Authorize Box button, system will redirect you to login page where you need to enter you box login credential and then a click grant access to box button.

      All folder present in box will be listed in Folders drop down. When you select any particular folder, all files present in that folder will appear in page block table. When you click on "View" link, file will open on right side of page.

      If you have box account, then use below url to test the functionality. Create folders in your box account and upload pdf and doc files in it. If you upload files with already existing file name in Box folder, then you will get error.

      https://skforce-developer-edition.ap1.force.com/skforce__boxauthpage

      I have built this page for demo. So every time you refresh this page, you need to again authorize it by clicking on Authorize box button. Actually I am not storing access token or refresh token or any user credentials and also scope of these variables are same as that of VF page. Also client id, client secret and access tokens are not displayed in demo page but if you follow all steps mentioned above including custom setting and remote site setting, then you will get complete UI.

      Important information which will help you to understand apex class:
      • Uploading data into box.com uses content type as multipart/form-data.
      • You can not send a file to server which is expecting a binary. So you need to encode the base64 in binary supported format.
      • In order to view document, first you need to send request to get temporary download URL by sending file id to Box.com. Temporary download URL is returned in response Location header. This URL can be used to download file.
      • Once you get temporary download URL, sent request to BOX.com to get temporary document id. In HTTPRequest, you need to pass temporary download URL in body.
      • Now this document id which you get in response can be used to generate session id for file which will be used to view file in iframe in VF page. When you do call out to get session id, pass temporary document id in request body.
      • If file is processed by Box.com and is ready to view, then in response you will get session id. If your request is accepted but file is not yet converted to HTML format then in response header, you will time duration after which file will be ready. This information is present in 'retry' header in response.
      • Once you get file session id from Box.com, then you use it view file in iframe in your VF page by using  URL: https://view-api.box.com/1/sessions/'+fileSessionId+'/view


      Notes:
      • You can upload any type of file to box folder.
      • Before uploading any file, please select folder in which you want to upload file.
      • As per my knowledge, View API doesn't support jpg and png images. 
      • You can easily view any pdf or word file from Box in SFDC using view api.
      • You can also specify download URL. Please refer Box content view API for this.
      • In apex, code is specified to get file download URL in FindFileDownloadUrl method in apex class.
      This blog will help you to basic understanding of how to achieve integration between Box and SFDC by using apex code. After going through this code, you can easily modify the code as per your requirements.

      Code for VF and apex class:



      Tuesday, April 28, 2015

      REST API TUTORIAL FOR SALESFORCE

      REST API provides a powerful, convenient, and simple Web services API for interacting with Force.com. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web 2.0 projects.

      A REST resource is an abstraction of a piece of information, such as a single data record, a collection of records, or even dynamic real-time information. Each resource in the Force.com REST API is identified by a named URI, and is accessed using standard HTTP methods (HEAD, GET, POST, PATCH, DELETE). The Force.com REST API is based on the usage of resources, their URIs, and the links between them. You use a resource to interact with your Salesforce or Force.com organization. For example, you can:
      •  Retrieve summary information about the API versions available to you.
      • Obtain detailed information about a Salesforce object such as an Account or a custom object.
      • Obtain detailed information about Force.com objects, such as User or a custom object.
      • Perform a query or search.
      • Update or delete records.


      In this blog, I will be explaining how to interact with Salesforce using REST API.  I will be creating a VF page named as “RESTAPIPlayground”. On this page you can specify different parameters which is required to send HTTPRequest like Access token, end point URL (URI), HTTP method etc. VF page will display the response from Salesforce and will also display the Apex code to send HTTPRequest.

      Here I assume that you are aware of how to generate access token from salesforce using oAuth2.0. If you want to learn this first then refer to my earlier blog:


      Once you have access token of salesforce with which you want to interact then you can use this playground (VF Page) to play with different options available under REST API.

      Create a Apex class "RESTAPIPlaygroundController" and VF Page "RESTAPIPlayground". Below is code for Apex Class and VF page.


      Below is snapshot of REST API Playground. You can specify the Access_Token, REST API service URI (endpoint URL), HTTP method and content type (json or xml), request body (in case of patch and post method). Once you click on send request, system will display the HTTP response.

      Note: Add the REST API service URI (end point URL) to remote site settings before sending HTTPRequest.




      Friday, April 24, 2015

      ACCESS TOKEN USING OAUTH 2.0 IN SALESFORCE

      OAuth (Open Authorization) is an open protocol to allow secure API authorization in a simple and standardized way from desktop and web applications. The Force.com platform implements the OAuth 2.0 Authorization Framework, so users can authorize applications to access Force.com resources (via the Force.com REST and SOAP Web Service APIs) or Chatter resources (via the Chatter REST API) on their behalf without revealing their passwords or other credentials to those applications. Alternatively, applications can directly authenticate to access the same resources without the presence of an end user.

      In this blog, I will be specifying different steps which we need to perform in order to generate Access token for Salesforce org. We will be using 2 different developer org. In org 1, we will be writing all code to generate access token for another org.

      In order to access token from different org and storing different required information, we will create custom object (External_Application__c) and create different fields mentioned below:

      Field Label
      Field Name
      Data Type
      Access Token
      Access_Token__c
      Text Area(255)
      Application Name
      Application_Name__c
      Text(255) (Unique Case Insensitive)
      Authorization Server Response
      Authorization_Server_Response__c
      Long Text Area(32768)
      Callback URL
      Callback_URL__c
      Text Area(255)
      Client ID
      Client_ID__c
      Text Area(255)
      Consumer secret
      Consumer_Key__c
      Text Area(255)
      ID
      ID__c
      Text Area(255)
      Instance URL
      Instance_URL__c
      Text Area(255)
      Issued at
      Issued_at__c
      Text Area(255)
      Outh Code
      Outh_Code__c
      Text Area(255)
      Refresh_Token
      Refresh_Token__c
      Text Area(255)
      Salesforce Domain
      Salesforce_Domain__c
      Text(255)
      Scope
      Scope__c
      Text(255)
      Signature
      Signature__c
      Text Area(255)


      Different steps involved in order to get access token:

      Login to developer organization (org 2) for which you want to generate access token.
      1. Navigate to Setup Create Apps, and in the Connected Apps section, click New to create a new connected app and click Enable OAuth Settings to open the API section.
      2. Specify name (here I am specifying "Rest Playground"), check enable OAuth settings checkbox and specify callback URL (in my case- https://xxx.salesforce.com/apex/WebServerAuthentication?AppName=SunilKumar04). here xxx refer to domain name for example ap1,ap2 etc.
      3. You may leave “Selected OAuth Scopes” blank.
      4. Click on Save. You will get consumer key and consumer secret key. Copy these 2 keys values and store it in notepad.


      Now login to developer organization (org 1) where you will be writing whole logic to find access
      token for org 2.
      • Create a custom button "Refresh Access Token" in External Application object. 

      • Create a VF page “WebServerAuthentication” and apex class “WebServerAuthenticationController”.

      • Add custom button "Refresh Access Token"  to External Application page layout.
      • Create Remote Site Settings records. Specify domain name of org 2 for which you want to fetch access token.

      • Now create a External Application records. Specify consumer key (generated while creatin connected app in org 2) in client id field. Enter consumer secret and callback URL as present in connect app record in org 2.


      Now we ready to generate access token which for org 2. Go to detail page of  record which you created. I have created record with name as "SunilKumar04".  Click on Refresh Access Token.
      System will redirect you to salesforce login page. Enter the credential of org 2 for which you want access token. After logging, if system ask any permission then click on Allow button. After that you will be redirected to org 1 and you can see the response details on External Application record detail page.



      Notes:

      • If you are integrating 2 developer org, then create domain in your developer org and use domain URL  as endpoint URL in Httprequest.
      • You can connect to different org. Create different records in External Application object for different org.
      • For more detailed information on obtaing access token, please refere below URL  https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com