Zoho CRM Scala SDK - Configuration and Initialization

Zoho CRM Scala SDK - Configuration and Initialization

Hello and welcome to another Kaizen week!

In this week's post, we'll show you how to get started with Zoho CRM's Scala SDK, and walk you through the configuration and initialization process. Specifically, we will  discuss how to use the Scala SDK to make API calls authenticated via self-client. Please note that this article holds true for Scala SDK supporting version 6 of Zoho CRM APIs.

Software Development Kits (SDKs) are sets of tools and libraries designed to simplify the development process, and the integration between applications and specific platforms or services. They provide pre-built functionalities and abstract complex tasks, facilitating easier and faster development process. Zoho CRM's Scala SDKs act as a wrapper  for the REST APIs, thus making it easier to use the services of Zoho CRM.

Simplified Authentication using Scala SDK

Authentication with Zoho CRM APIs is facilitated by the OAuth 2.0 protocol, ensuring secure access to its resources. The process begins with the generation of a grant token for your organization in the Zoho Developer Console, where you specify the required scopes. Subsequently, using this grant token, you can generate both the access token, used for API call authentication, and the refresh token, employed for refreshing the access tokens after their one-hour expiry period. You must persist these tokens, along with their expiry times, in your server's data store for seamless API access. 

However, with the Scala SDK, this authentication process is significantly simplified. After generating the grant token and initialization, the SDK takes care of the rest. The SDK handles token generation, persistence, and refreshing the access token automatically, ensuring access to the resources without manual intervention.

Using the Zoho CRM Scala SDK

Before diving into the usage of Scala SDKs, ensure that the following prerequisites are met:
  • Ensure that the client app has Java version 11 or above.
  • Ensure that the client app has Scala version 2.13.5 or above.
  • Have an IDE such as IntelliJ installed.
  • An active Zoho CRM account.

1. Register your application with Zoho CRM

When you register a client with Zoho CRM, you establish a connection between your application and Zoho CRM, enabling your application to securely access and interact with Zoho CRM APIs and resources after authentication. The registration process involves providing essential details such as the client type, homepage URL, and authorized redirect URIs, depending on the type of client you choose.

To register your client:
  1. Go to the Zoho Developer Console
  2. Click on Get Started or +ADD CLIENT
  3. Choose the Client Type as Self-Client or Server based Applications depending on your application. Read our Kaizen post on the different client types to understand better. For this article, we will proceed with Self-client as we aim to develop a Scala application for our own use.
  4. Fill in the necessary details and click CREATE to register your client successfully. This will provide you with a Client ID and Client Secret.

2. Create a Scala project in your preferred IDE

If you already have your project set up, you may skip this step. However, if you are starting out, the next crucial step is to create a Scala Project in your preferred IDE. For the purpose of this guide, we will be using IntelliJ IDEA as the IDE of choice. 

3. Include the Zoho CRM Scala SDK in your project

To include the Zoho CRM Scala SDK in your project, you can follow different methods as outlined here.  However, for the purpose of this guide, we will demonstrate how to include the SDK using the build.sbt file.

Follow these steps to include the Zoho CRM Scala SDK in your project using the build.sbt file:
  1. Open your project in IntelliJ IDEA or your preferred IDE.
  2. Locate the build.sbt file in your project directory.
  3. Add the Zoho CRM Scala SDK dependency to your build.sbt file. To add the latest version (supporting version 6 of Zoho CRM APIs), include this line in the file  and Save: libraryDependencies ++= Seq( "com.zoho.crm" % "zohocrmsdk-6-0" % "2.0.0")
  4. Sync the changes and reload the files to ensure that the SDK has been added to the project.
Please note that when you install the Zoho CRM SDK, there are many dependencies which will also be installed. These dependencies are necessary for the proper functioning of the SDK and will be automatically managed by your build tool (such as sbt) during the installation process.


4. Obtain the grant token to authenticate your client

To make API calls, you need to authenticate your client by generating a grant token with the required scopes. For this guide, we will be using the self-client created in the first step. 
Log in to the Zoho Developer Console, and generate the grant token with the required scopes. Please note that this grant token has a short life span, and that it is used to generate the access and refresh tokens. Refer to our Kaizen on OAuth2.0 for more details.


5. Configuration and Initialization of the SDK

The configuration step in initializing the SDK involves setting up various objects to define how the SDK operates. This includes specifying the domain for API calls, token persistence, error logging, resource information storage, and more.

Before going into the specifics of various configurations, let us first discuss Token Persistence. Token Persistence refers to the mechanism through which access tokens and refresh tokens obtained during authentication are stored and managed by the SDK.  By storing tokens securely, the SDK can automatically manage token expiration and renewal, eliminating the need for manual token handling by the developer.For details on the different persistence methods supported by our SDKs, please refer to the last section of this post. In this guide, we will be using File Persistence as the method for Token Persistence. However, please note that users must choose the method that best suits their requirements and preferences.

Here is a sample code to initialize the SDK. Make sure to replace the client ID, client secret, grantToken, file paths, and other configurations with your specific values. 
  1. import com.zoho.api.authenticator.OAuthToken
  2. import com.zoho.crm.api.dc.USDataCenter
  3. import com.zoho.crm.api.exception.SDKException
  4. import com.zoho.crm.api.{HeaderMap, Initializer, SDKConfig}
  5. import com.zoho.api.logger.Logger
  6. import com.zoho.api.authenticator.store.FileStore

  7. object BulkWrite {
  8.   @throws[SDKException]
  9.   def main(args: Array[String]): Unit = {
  10.     val environment = USDataCenter.PRODUCTION
  11.     val token = new OAuthToken.Builder().clientID("1000.xxx").clientSecret("xxx").grantToken( "1000.xxx").findUser(false).build()
  12.     //Object containing the absolute file path to store tokens
  13.     var tokenstore = new FileStore("/Documents/SDK-Projects/Scala-SDK/ScalaSample/sdk_tokens_new.txt")
  14.     var logger = new Logger.Builder()
  15.       .level(Logger.Levels.ALL)
  16.       .filePath("/Documents/SDK-Projects/Scala-SDK/ScalaSample/scala_sdk_log.log")
  17.       .build
  18.     var sdkConfig = new SDKConfig.Builder().pickListValidation(false).autoRefreshFields(false).connectionTimeout(1000).requestTimeout(1000).socketTimeout(1000).build
  19.     new Initializer.Builder().environment(environment).token(token).store(tokenstore).logger(logger).SDKConfig(sdkConfig).initialize()
  20.   }
  21. }
  22. class BulkWrite {}

During the initialization step, the following configuration details have to be defined to configure the  behavior and functionality of the SDK. While two of them are mandatory, the others are optional.
  1. environment (mandatory): It determines the API environment, which dictates the domain and URL for making API calls. The format follows the Domain.Environment pattern.
    eg : val env = USDataCenter.PRODUCTION
  2. token (mandatory) : Contains the user token details. Create an instance of OAuthToken with the details that you get after registering your Zoho client. Depending on the available tokens, you can select one of the following flows:
    1. Grant Token Flow: Involves storing and persisting the grant token. This flow is used when you have a grant token available. The SDK will generate and persist the access and refresh tokens, and also refresh the access token upon expiry.
    2. Refresh Token Flow: Involves storing and persisting the refresh token. This flow is used when you have a refresh token available. The SDK will generate and persist the access and refresh tokens, and also refresh the access token upon expiry.
    3. Access Token Flow: In this flow, the access token is directly utilized for API calls without token persistence. The SDK will persist the access token, but upon expiry it won't be refreshed, and an INVALID_TOKEN error will be thrown once the access token has expired.
    4. Id FLow : You can use the id from the persisted token file/DB to make API calls. The id is a unique system generated value for each token details entry in the file/DB. Please note that you can use this method only after the SDK has already been initialized.
  3. logger (optional) : You can customize the logging behavior by setting the desired log level, which can be one of the following: FATAL, ERROR, WARNING, INFO, DEBUG, TRACE, ALL, or OFF. Additionally, you can configure the file path and file name for the log file.
  4. store (optional) : Allows you to configure token persistence for your application. If this is skipped, the SDK will create the "sdk_tokens.txt" file in the current working directory by default to persist the tokens. 

    Database Persistence
    File Persistence
    Custom Persistence
    var tokenstore = new DBStore.Builder()
      .host("hostName")
      .databaseName("databaseName")
      .tableName("tableName")
      .userName("userName")
      .password("password")
      .portNumber("portNumber")
      .build
    var tokenstore = new FileStore("/Users/user_name/Documents/scala_sdk_token.txt")
    var tokenStore = new CustomStore()

  5. SDKConfig (optional) : This method takes care of additional SDK configurations.

    Configuration Key
    Description
    autoRefreshFields
    Default Value : False
    A boolean configuration field to enable or disable automatic refreshing of module fields in the background. If set to true, fields are refreshed every hour, and if set to false, fields must be manually refreshed or deleted.
    pickListValidation
    Default Value : True
    This field enables or disables pick list validation. If enabled, user input for pick list fields is validated, and if the value does not exist in the pick list, the SDK throws an error. If disabled, the input is not validated and the API call is made.
    enableSSLVerification
    Default Value : True
    A boolean field to enable or disable curl certificate verification. If set to true, the SDK verifies the authenticity of certificate. If set to false, the SDK skips the verification.
    connectionTimeout
    Default Value : 0
    The maximum time (in seconds) to wait while trying to connect. Use 0 to wait indefinitely.
    timeout
    Default Value : 0
    The maximum time (in seconds) to allow cURL functions to execute. Use 0 to wait indefinitely.

  6. requestProxy (optional) : Configure this only if you're using a proxy server to make the API calls. To configure, create an instance of RequestProxy containing the proxy properties of the user.

    var requestProxy = new RequestProxy.Builder()
      .host("proxyHost")
      .port(80)
      .user("proxyUser")
      .password("password")
      .userDomain("userDomain")
      .build()

  7. resourcePath (optional) : To configure the absolute directory path to store user-specific files containing module fields information. If this object is skipped, the files will be stored in the project directory itself.
Once the initialization is successful, you can verify that the access and refresh tokens are generated and persisted. You can do this by checking the tokens file or the database, depending on the token persistence method you configured during initialization.


Token Persistence

There are three token persistence methods supported by our SDKs. 
  1. Token Persistence using a Database : In Database persistence, tokens are stored and retrieved from a database (e.g., MySQL). In this case, you should create a table in your database with the required columns. The custom database name and table name can be set in DBStore instance, when you initialise the SDK.
    For instance, to persist your tokens in a table named token in database named zoho in your mySQL DB, use this:

    CREATE DATABASE zoho; // use this to create database named zoho
    // use this to create a table named token, with the following necessary columns
    CREATE TABLE token ( 
      id varchar(10) NOT NULL,
      user_name varchar(255) NOT NULL,
      client_id varchar(255),
      client_secret varchar(255),
      refresh_token varchar(255),
      access_token varchar(255),
      grant_token varchar(255),
      expiry_time varchar(20),
      redirect_url varchar(255),
      api_domain varchar(255),
      primary key (id)
    );

  2. File Persistence : This method allows storing and retrieving the authentication tokens from the file in the file path that you configure. The file will contain the id, user_name, client_id, client_secret, refresh_token, access_token, grant_token, expiry_time, redirect_url, and api_domain.
  3. Custom Persistence : This is a method where users can create their own method of storing and retrieving authentication tokens. To use this method, users need to implement the TokenStore interface and override its methods according to their own logic. For more details, please refer here.
We hope that you found this useful. In next week's Kaizen post, we will discuss about Bulk Write operations using the Scala SDK for Zoho CRM, and on how to import both parent and child records in a single operation.

If you have any queries, let us know the comments below, or send an email to support@zohocrm.com. We would love to hear from you. 


Cheers!
Anu Abraham



Recommended Reads:





    Access your files securely from anywhere

          Zoho Developer Community




                                    Zoho Desk Resources

                                    • Desk Community Learning Series


                                    • Digest


                                    • Functions


                                    • Meetups


                                    • Kbase


                                    • Resources


                                    • Glossary


                                    • Desk Marketplace


                                    • MVP Corner


                                    • Word of the Day



                                        Zoho Marketing Automation


                                                Manage your brands on social media



                                                      Zoho TeamInbox Resources

                                                        Zoho DataPrep Resources



                                                          Zoho CRM Plus Resources

                                                            Zoho Books Resources


                                                              Zoho Subscriptions Resources

                                                                Zoho Projects Resources


                                                                  Zoho Sprints Resources


                                                                    Qntrl Resources


                                                                      Zoho Creator Resources



                                                                          Zoho Campaigns Resources


                                                                            Zoho CRM Resources

                                                                            • CRM Community Learning Series

                                                                              CRM Community Learning Series


                                                                            • Kaizen

                                                                              Kaizen

                                                                            • Functions

                                                                              Functions

                                                                            • Meetups

                                                                              Meetups

                                                                            • Kbase

                                                                              Kbase

                                                                            • Resources

                                                                              Resources

                                                                            • Digest

                                                                              Digest

                                                                            • CRM Marketplace

                                                                              CRM Marketplace

                                                                            • MVP Corner

                                                                              MVP Corner





                                                                                Design. Discuss. Deliver.

                                                                                Create visually engaging stories with Zoho Show.

                                                                                Get Started Now


                                                                                  Zoho Show Resources


                                                                                    Zoho Writer Writer

                                                                                    Get Started. Write Away!

                                                                                    Writer is a powerful online word processor, designed for collaborative work.

                                                                                      Zoho CRM コンテンツ






                                                                                        Nederlandse Hulpbronnen


                                                                                            ご検討中の方





                                                                                                  • Recent Topics

                                                                                                  • Client Script - mapping data from different module

                                                                                                    Dear ZOHO Team Firstly I need to describe the need - I need to have data from Contacts module based on lookup field - the 5 map limit is not enough for me because I have almost 20 fields to copy So I have decided to make a Customer Script - and from unknown
                                                                                                  • DORA compliance

                                                                                                    For DORA (Digital Operational Resilience Act) compliance, I’ll want to check if Zoho provides specific features or policies aligned with DORA requirements, particularly for managing ICT risk, incident reporting, and ensuring operational resilience in
                                                                                                  • Files Uploaded to Zoho WorkDrive Not Being Indexed by Search Engines

                                                                                                    Hello, I have noticed that the files I upload to Zoho WorkDrive are not being indexed by search engines, including Google. I’d like to understand why this might be happening and what steps I can take to resolve it. Here are the details of my issue: File
                                                                                                  • Zoho Creator Upcoming Updates - December 2024

                                                                                                    Hi all, We're excited to be back with the latest updates and developments on the Creator platform. Here's what we're going over this month: Deluge AI assistance Rapid error messages in Deluge editor QR code & barcode generator Expandable RTF and multi
                                                                                                  • Customer can't comment on SO or Invoice

                                                                                                    Hi I just saw that my customers are not able to submit a comment either on invoices or sales order. What happens if my customer hits submit is just nothing. only a red line appears on top of the page which probalby indicates an error. I'm not able to
                                                                                                  • Zoho Creator customer portal limitation | Zoho One

                                                                                                    I'm asking you all for any feedback as to the logic or reasoning behind drastically limiting portal users when Zoho already meters based on number of records. I'm a single-seat, Zoho One Enterprise license holder. If my portal users are going to add records, wouldn't that increase revenue for Zoho as that is how Creator is monetized? Why limit my customer portal to only THREE external users when more users would equate to more records being entered into the database?!? (See help ticket reply below.)
                                                                                                  • See Calendar When Creating Meetings On Record Page

                                                                                                    It would be a great user experience to see you calendar while you are creating a meeting on a record page. Here is how I imagine it could look:
                                                                                                  • Saved filters, layout rule support, related list quick navigation, and more

                                                                                                    Hello Everyone, We're excited to share some new features and enhancements in the Zoho CRM iOS and Android apps that will improve your mobile experience. These updates will make your CRM journey more efficient and user-friendly. Here's a look at what's
                                                                                                  • Power of Automation: Automatically send an email to all portal users with today's list of Open tasks.

                                                                                                    Hello Everyone, A Custom Function is a user-written set of code to achieve a specific requirement. Set the required conditions needed as to when to trigger using the Workflow rules (be it Tasks / Project) and associate the custom function to it. Requirement:-
                                                                                                  • Introduction of Robotics Process Automation in Zoho products

                                                                                                    It will be great if Zoho can start advancing from automation to robotics process automation. For a start, it can be started with smart document understanding. Provide OCR engines Google cloud, Microsoft Azure Computer vision OCR, Microsoft OCR, Omnipage
                                                                                                  • Lock a custom field on a deal record but keep all other fields editable?

                                                                                                    I have a custom field, which auto-populates a job number upon converting a lead to a deal but the automation breaks if someone accidentally edits that field. I want to lock that field but keep all other fields open. Is this possible? I've tried through
                                                                                                  • Add Feature To Hide Plugin Sections On Record View

                                                                                                    Hi team, I'm trying to help a client tidy up their CRM. When it comes to record view some sections and fields are visible no matter what Layout Rules are applies and they are not removeable from the layout editor. I would like to see an option to hide
                                                                                                  • Creator Simplified #10: Predefine Form Field Values and Make Them Read-Only for Users

                                                                                                    Hey Creators, Ready for this week's tip in the Creator Simplified series? Today, we will explore how to have read only fields in a form. Use Case: Assume a scenario where the default value for a Department field needs to be English Literature, but you
                                                                                                  • Problem configuring/customizing sales pipeline steps

                                                                                                    Hello, I have created several sales pipelines with different stages in them. Unfortunately I forgot to properly configure these steps (conversion probability, forecast category). How can I modify and customize all these steps? Thnak you by advance M
                                                                                                  • fetch records from analytics table from creator

                                                                                                    I have a creator workflow that I am working in that will compare data from within the app to a table in zoho analytics. Is there a way to fetch a record from Analytics? I have attempted a custom connector with analytics and tried to use it with invoke
                                                                                                  • Directly Edit, Filter, and Sort Subforms on the Details Page

                                                                                                    Hello everyone, As you know, subforms allow you to associate multiple line items with a single record, greatly enhancing your data organization. For example, a sales order subform neatly lists all products, their quantities, amounts, and other relevant
                                                                                                  • Ability to Change Custom View After Cadence Creation

                                                                                                    Dear Zoho Team, I hope you are well. We would like to request an enhancement to the Cadence feature in Zoho CRM. Currently, during the creation of a Cadence, we can select a Custom View under the "Who is this for?" section. However, once the Cadence is
                                                                                                  • Zoho Creator Integration with QuickBooks: A Step-by-Step Guide

                                                                                                    Introduction: Integrating Zoho Creator with QuickBooks allows you to sync your business data between the two platforms, providing a seamless experience for managing accounting, invoicing, and financial data. This integration helps automate workflows and
                                                                                                  • Note not being pulled for other modules in email template

                                                                                                    Hi there, Currently i am creating an email template that is able to pull the data from notes field in estimate module and email it to procurement team where they will be able to receive the email with the contents of the note, i am unable to replicate
                                                                                                  • No Sales Returns on SO's with Dropped Shipped items + Inventory Items

                                                                                                    We have encountered an issue in Zoho related to sales orders that include both dropshipped items and inventory items. Specifically, it is currently not possible to create sales returns for the company’s own inventory items from these sales orders. This
                                                                                                  • Pre-fill TO and CC fields for Email Templates

                                                                                                    This would be a game changer to be able to set either specific email addresses or merge fields based on deal role titles into email templates. Please pass this along to *hopefully* add to future features of Zoho CRM.
                                                                                                  • Pick list - Cannot save list "Special Characters not Allowed" error message

                                                                                                    Bulk uploading values. All values are pretty standard - with the exception of a "-" (dash). Like:  Industry - Prepared Food Is the simple dash a special character too? Jan
                                                                                                  • Whatsapp Limitation Questions

                                                                                                    Good day, I would like to find out about the functionality or possibility of all the below points within the Zoho/WhatsApp integration. Will WhatsApp buttons ever be possible in the future? Will WhatsApp Re-directs to different users be possible based
                                                                                                  • Flow with CRM

                                                                                                    Hello, I have a simple flow that uses a web hook to enter data into a Sales Order. I have the web hook sending Flow data which has a PO field. If the PO has a special character like - or / or \ the task fails. How can I get the flow to be okay with the
                                                                                                  • Making the Resolution Tab Mandatory

                                                                                                    Hello Everyone! This edition is here to show you how to make the Resolution mandatory when closing a ticket. The Ticket Resolution tab helps keep a record of the solution provided for the ticket query. The resolution can serve as a quick reference to
                                                                                                  • Remove County field from Customer Address input screen (or allow input to be deleted)

                                                                                                    We are in the USA and have just noticed that there is now a County field in the Customer Address input screen (and maybe other areas of Zoho Books, but this is the one affecting us at the moment). County is not important to our business, and in fact we
                                                                                                  • Notificación de cumpleaños

                                                                                                    Hola: Se puede enviar alguna alerta de felicitación al personal que cumple años, que se dispare solo? Si existe como se puede hacer? Saludos
                                                                                                  • Automation#25: Move Tickets to Unassigned When the Owner Is Offline

                                                                                                    Hello Everyone, Welcome to this week's Community Series! 'Tis the holiday season—a time when work often takes a brief pause. The holiday spirit is in full swing at Zylker Techfix too, with employees taking some well-deserved time off. During this period,
                                                                                                  • Callback URLs

                                                                                                    I need to connect to an external service through an API that requires me to provide a Callback URL so that a status update can be sent back when the API request has been processed. Is there a way to do this in Creator without having to use a middleware
                                                                                                  • Email signature not being included if user creates ticket / sends email

                                                                                                    When I create a ticket (send email), the signature doesn't appear to be added to the ticket. Can you confirm if this is the case? It would obviously be useful to include the user's signature even when sending a client an email and not only on replie
                                                                                                  • Zoho Notebook window ignores taskbar

                                                                                                    When maximized to full screen, the Zoho Notebook window ignores the presence of the taskbar and overlaps it. What could be the problem? Linux Mint 22 Cinnamon. Zoho Notebook 3.2.0
                                                                                                  • Document images

                                                                                                    We used to be able to rotate the images but this has now been removed ???
                                                                                                  • VENDORS ARE NOT SYNCHED WITH CONTACTS IN CRM

                                                                                                    Hello, While the ACCOUNTS and CONTACTS (Including the primary contact) are synced with the CONTACTS module in CRM, the vendor's CONTACTS are not synced with CRM - which basically forces the users to re-enter all vendor's contacts twice and then update
                                                                                                  • Involved account types are not applicable when create journals

                                                                                                    { "journal_date": "2016-01-31", "reference_number": "20160131", "notes": "SimplePay Payroll", "line_items": [{ "account_id": "538624000000035003", "description": "Net Pay", "amount": 26690.09, "debit_or_credit": "credit" }, { "account_id": "538624000000000403", "description": "Gross", "amount": 32000, "debit_or_credit": "debit" }, { "account_id": "538624000000000427", "description": "CPP", "amount": 1295.64, "debit_or_credit": "debit" }, { "account_id": "538624000000000376", "description":
                                                                                                  • KB Templates

                                                                                                    * It would be nice if Zoho can provide users an option to create custom templates for KB articles. Also, it would be nice as well if the users can have an option to 1.) select a default template and 2.) declare default tag/tags, for KB articles created through Ticket's resolution.
                                                                                                  • Zoho CRM Reports Module on Mobil App

                                                                                                    I have the mobile app and the reports module doesn't appear in the sidebar for some reason. I saw a Youtube video where the user had the Reports module on mobile. Is there a setting to show it on mobile? Thanks.
                                                                                                  • Contacts Don't Always Populate

                                                                                                    I've noticed that some contacts can easily be added to an email when I type their name. Other times, a contact doesn't appear even though I KNOW it is in my contact list. It is possible the ones I loaded from a spreadsheet are not an issue and the ones
                                                                                                  • Zoho Projects Android app update - List view enhancement

                                                                                                    Hello, everyone! In the latest android version(v3.9.15) of the Zoho Projects app update, we have enhanced the List view of tasks. We have also introduced a complete scroll of the tasks in the list view without scrolling the task fields(status, start date,
                                                                                                  • Print PO receipt

                                                                                                    Hi I would like to print the PO receipt. There does not seem to be any way to do this. I track batch numbers and printing the PO does not show this. Only the receipt would show the details of the receipt. Currently I print the screen which does not have
                                                                                                  • On the US Data Centre rather than the UK but dont know how to migrate it

                                                                                                    We have a new staff member with an external email address and cant add them to Zoho chat - we have been told its becuase we are in the UK but on a US Data centre - we therefore need to change it but no idea how to can anyone else as we are going round
                                                                                                  • Next Page