Kaizen #44 - Handling Attachments API in Java and Java SDK (Part 1/2)

Kaizen #44 - Handling Attachments API in Java and Java SDK (Part 1/2)

Hello everyone!

Welcome back to yet another post in the Kaizen series.
This week, we will discuss about the attachments API in Java and Java SDK.

1. Introduction to Attachments API

Attachments in Zoho CRM are an important aspect of any record as they add additional information in the form of documents such as Marketing Collateral, Sales Quotes/Orders/Invoices, SLA and etc to the existing record. A record can contain multiple attachments. However, the attachments hold a maximum limit per record. The attachment limit per record is 100Mb. It can be either a single file or multiple files. In the case of multiple files, the total file size of the multiple files must not exceed 100Mb. The allowable limit for an image is 10Mb, and the resolution is 10megapixel. 

Let's discuss some important details concerning the attachments API. 
i. While uploading an attachment or an image through a curl request, the image must be included in the request with the content type as multipart/form-data

ii. The oauth scopes required for attachment API : 
ZohoCRM.modules.all 
(or) 
ZohoCRM.modules.{module_name}.{operation_type}
(and) 
ZohoCRM.modules.attachments.all

iii. The possible oauth scope module_names are: 
leads, accounts, contacts, deals, campaigns, tasks, cases, events, calls, solutions, products, vendors, pricebooks, quotes, salesorders, purchaseorders, invoices, custom, and notes.

2. Operations in the Attachments API

The attachments API in Zoho CRM allows a user to get a list of attachments, upload or download a file and delete them as well. Our focus for this week will be on executing the following operations using Java's HTTP client and CRM's Java SDK.
a. List attachments
b. Upload attachments

a. List Attachments

To get the list of attachments of a specific record. 

Request method:  GET
Request URL:  
{{api-domain}}/crm/v2/{module_api_name}/{record_id}/attachments

Sample URL:
{{api-domain}}/crm/v2/Leads/3719520000000659047/attachments

Java SDK Code -
In Java SDK, we employ the getAllAttachmentsDetails() method to fetch all the necessary details. We will need the record_id for whom the attachment details are fetched. Here, the record_id provided is 3719520000000659047. After fetching the details, we iterate over the response and just print the necessary details. 
public void getAllAttachmentsDetails() throws Exception {
              ZCRMRecord record=ZCRMRecord.getInstance("Leads",3719520000000659047L); 
 int page=1;
              int per_page=200;
 BulkAPIResponse responseIn=record.getAllAttachmentsDetails(page, per_page,null);
        List <ZCRMAttachment> attchments=(List<ZCRMAttachment>)responseIn.getData(); 
        if(attchments!=null) 
        {
            for(ZCRMAttachment attchmentIns : attchments)
            {
                System.out.println(attchmentIns.getId()); 
                System.out.println(attchmentIns.getFileName()); 
                System.out.println(attchmentIns.getFileType());
                System.out.println(attchmentIns.getSize()); 
                ZCRMRecord parentRecord1=attchmentIns.getParentRecord();
                System.out.println(parentRecord1.getEntityId());
                ZCRMUser createdBy1=attchmentIns.getCreatedBy();
                System.out.println(createdBy1.getId()); 
                System.out.println(createdBy1.getFullName());
                ZCRMUser modifiedBy1=attchmentIns.getModifiedBy();
                System.out.println(modifiedBy1.getId()); 
                System.out.println(modifiedBy1.getFullName());
                ZCRMUser owner1=attchmentIns.getOwner();
                System.out.println(owner1.getId()); 
                System.out.println(owner1.getFullName()); 
                System.out.println(attchmentIns.getCreatedTime()); 
                System.out.println(attchmentIns.getModifiedTime()); 
            }
        }
}


Java Code 
In the absence of Java SDK, we make a GET request to the mentioned URL and display the response.
public void getAllAttachmentDetails() throws Exception
 {
  CloseableHttpClient httpclient = HttpClients.createDefault();
     HttpGet httpget = new HttpGet("{{api-domain}}/crm/v2/Leads/3719520000000659047/attachments");
     httpget.addHeader("Authorization", "Zoho-oauthtoken 1000.9XXX.6XXX");
     System.out.println("Request Type: "+httpget.getMethod());
     HttpResponse httpresponse = httpclient.execute(httpget);
     Scanner sc = new Scanner(httpresponse.getEntity().getContent());
     System.out.println(httpresponse.getStatusLine());
     while(sc.hasNext()) {
          System.out.println(sc.nextLine());
     }
 }


Sample Response
{
    "data": [
        {
            "Owner": {
                "name": "Patricia Boyle",
                "id": "3719520000000191015",
                "email": "patricia.boyle@zohocorp.com"
            },
            "Modified_Time": "2020-08-12T10:28:07+05:30",
            "File_Name": "testimg.jpg",
            "Created_Time": "2020-08-12T10:28:07+05:30",
            "Size": "120335",
            "Parent_Id": {
                "name": "Johnson Charles",
                "id": "3719520000000659047"
            },
            "$editable": true,
            "$file_id": "8urshba63343dcc7b41418d74eeca1d4c323e",
            "$type": "Attachment",
            "$se_module": "Leads",
            "Modified_By": {
                "name": "Patricia Boyle",
                "id": "3719520000000191015",
                "email": "patricia.boyle@zohocorp.com"
            },
            "$state": "save",
            "id": "3719520000000981001",
            "Created_By": {
                "name": "Patricia Boyle",
                "id": "3719520000000191015",
                "email": "patricia.boyle@zohocorp.com"
            },
            "$link_url": null
        }
    ],
    "info": {
        "per_page": 200,
        "count": 2,
        "page": 1,
        "more_records": false
    }
}

b. Upload Attachments

To attach a file to a record.

Request method :  POST
Request URL:
{{api-domain}}/crm/v2/{module_api_name}/{record_id}/attachments

Sample URL:
 
{{api-domain}}/crm/v2/Leads/3719520000000659047/attachments

Java SDK Code
For uploadAttachment(), we need the record_id and the file to upload as a pre-requisite. We employ the uploadAttachment() to upload our file to the record.
public void uploadAttachment() throws Exception{
  ZCRMRecord record=ZCRMRecord.getInstance("Leads",3719520000000659047L); 
  APIResponse responseIn=record.uploadAttachment("/Users/srivathsan-8829/Downloads/record.txt"); 
  System.out.println( "Status:"+ responseIn.getMessage()); 
        System.out.println( "Message:"+ responseIn.getStatus()); 
        System.out.println("http code"+ responseIn.getStatusCode()); 
        System.out.println( " Code:"+responseIn.getResponseJSON().toString());
 }


Java Code 

Uploading an attachment to a record in Java without Java SDK can be a tedious task. As shown below, the request needs to be multipart request. 

public void uploadAttachments() throws Exception
 {
    CloseableHttpClient httpclient = HttpClients.createDefault();
       File file = new File("/Users/srivathsan-8829/Downloads/record.txt");
       FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);
       MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
       entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
       HttpEntity mutiPartHttpEntity = entitybuilder.build();
       RequestBuilder reqbuilder = RequestBuilder.post("{{api-domain}}/crm/v2/Leads/3719520000000659047/attachments");
       reqbuilder.setEntity(mutiPartHttpEntity);
       reqbuilder.addHeader("Authorization", "Zoho-oauthtoken 1000.9XXX.6XXX");
       HttpUriRequest multipartRequest = reqbuilder.build();
       HttpResponse httpresponse = httpclient.execute(multipartRequest);
       System.out.println(EntityUtils.toString(httpresponse.getEntity()));
       System.out.println(httpresponse.getStatusLine());
 }

Sample Response
{
    "data": [
        {
            "code": "SUCCESS",
            "details": {
                "Modified_Time": "2020-08-12T10:28:07+05:30",
                "Modified_By": {
                    "name": "Patricia Boyle",
                    "id": "3719520000000191015"
                },
                "Created_Time": "2020-08-12T10:28:07+05:30",
                "id": "3719520000000981001",
                "Created_By": {
                    "name": "Patricia Boyle",
                    "id": "3719520000000191015"
                }
            },
            "message": "attachment uploaded successfully",
            "status": "success"
        }
    ]
}

Note :-
FILE_SIZE_MORE_THAN_ALLOWED_SIZE - This error is specific to the attachments API which is returned when you try to upload an attachment/photo exceeding the allowed size.

We hope you found this post useful. In our next kaizen post, we will discuss how to download and delete an attachment via Java HTTP Client and Java SDK. Let us know your thoughts in the comment section or reach us out at support@zohocrm.com.

Cheers!







    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

                                                                                                  • Project Billing with the Staff Hours Method in Zoho Projects

                                                                                                    The Staff Hours Billing Method in Zoho Projects allows you to bill your clients based on the actual time spent by each team member on a project, at the rate set for each user. This is useful for projects where different skill sets are needed and service
                                                                                                  • Creator Subform to CRM Subform

                                                                                                    Hello all, Has anyone successfully written data from a Creator Subform into CRM subform? I have been able to get the rows to populate but none of the data will come through. I'll add my code and the result in CRM. Creator Subform is 'Delivery_Receiving_Hours'.
                                                                                                  • custom fields not populating from deluge script into invoice

                                                                                                    Hello, I've created some Deluge script that is meant to take a few inputted invoice custom fields and calculate a few others. I can see when I execute the function that my inputted custom fields are being passed, yet im still ending up with all "null"
                                                                                                  • tax summation function - getting error

                                                                                                    Hello, I'm trying to create a function that adds all of individual tax rates from a few jurisdictions. I'm getting an error on line 9 - Value is empty and 'get' function cannot be applied. I've checked that I have data in each of the required fields,
                                                                                                  • Backstage / Zoho Books integration

                                                                                                    Hello. We have Zoho One and have slowly started using Backstage. Loving it. Problem is, we have ZERO accounting control over what is sold through this product. When will we be able to connect it to our existing Zoho Books tenant? Thank you very much!
                                                                                                  • Getting list of calendar events over api for zoho mail calendar

                                                                                                    Hi, I am using just Zoho mail without using Zoho CRM. I wanted to get all events booked in my zoho mail calendar through an api at regular intervals. I could find such API support for Zoho CRM calendar but not for zoho mail calendar. Can you kindly let
                                                                                                  • Allocate emails to user in a shared mailbox

                                                                                                    Hi, This might be obvious, but I cannot find the answer. I have 3 shared mailboxes so any team member can see the emails. Is there a way of allocating a specific email to a user so that it is their responsibility to deal with it? Thanks in advance.
                                                                                                  • Introducing Zoho Campaigns' own gateway for SMS campaigns

                                                                                                    We are excited to announce the launch of our SMS Gateway to send SMS through Zoho Campaigns. We have also made a few other changes in our current SMS Campaign model to improve your over all user experience. These updates are planned with an aim to expand
                                                                                                  • Update a lookup field in CRM from Creator using deluge

                                                                                                    I have a Creator form that creates a new account. When it creates the new account in the Accounts Module, I need it to also populate the Parent Account, which is a lookup field coming from the Module Parent Accounts, field Parent Account Name. I have
                                                                                                  • SMS Keyword Tracking in Zoho CRM From Zoho Campaigns

                                                                                                    Is there a way to track SMS leads in campaigns by associating them with specific keywords or codes? Additionally, can these leads be pushed to the CRM while retaining the keyword for tracking and reporting purposes?
                                                                                                  • Projects Multiselect API

                                                                                                    Having troubles setting a mutli select field via API. updateMap = map(); updateMap.put("UDF_MULTI1","picklist_id1,picklist_id2"); updateProjectRes = invokeurl [ url :"https://projects.zoho.com/restapi/portal/XXXX/projects/" + projectID + "/" type :POST
                                                                                                  • Bill quantity received / PO quantity

                                                                                                    PO's are raised & often the quantity received is greater than the PO quantity, so when we receive the bill & adjust the quantity on the bill we get.... Quantity recorded cannot be more than quantity ordered. This necessitates the adjustment of the PO
                                                                                                  • ZOHO BOOKS - RECEIVING MORE ITEMS THAN ORDERED

                                                                                                    Hello, When trying to enter a vendor's bill that contains items with bigger quantity than ordered in the PO (it happens quite often) - The system would not let us save the bill and show this error: "Quantity recorded cannot be more than quantity ordered." 
                                                                                                  • Adding Bluesky channel

                                                                                                    Hello, Is Bluesky (AT protocol) soon added on Social ? Bluesky is being developped and is now open to anyone (no more invitation) Thank you
                                                                                                  • Using Queries with dynamic parameters in Kiosk Studio

                                                                                                    Hi, I'm pretty new when it comes to developing within Zoho (I'm really a .NET developer), as it was just added to my responsibilities. For a new feature in the CRM, I'm trying to develop a Kiosk function to show a list of records (retrieved by the new
                                                                                                  • Unused items should not count into the available number of custom fields

                                                                                                    Hey, I realized that unused Items reduce the number of available custom fields. I can't see a case where that makes sense. Especially in our case where we have two different layouts in Deals with a lot of different fields, this causes problems.
                                                                                                  • Introducing Bot Filtering for Accurate Email Campaign Analytics

                                                                                                    Dear Marketers, We're excited to announce a new feature designed to enhance the accuracy of your email campaign analytics: bot filtering. This feature helps you filter out bot-generated opens and clicks, ensuring your campaign reports reflect genuine
                                                                                                  • Tip 37: Time Log Restriction in Zoho Projects

                                                                                                    Timesheet in Zoho Projects helps you big time in entering log hours for the tasks and issues and approving them. Now, with the new Time Log Restriction option, you can set daily and weekly log hour limits. You can restrict users from entering extra log hours than the permissible limit. The limits are restricted to 24 hours per day and 168 hours per week by default based on business hours. To customize, navigate to Task & Timesheet settings under Portal Configuration in Zoho Projects setup and enable
                                                                                                  • Chart showing schedule

                                                                                                    I want to be able to create a chart for everyday to check and which of which driver is available on the timeframe. Here's my table Name City Day Start Time End Time Driver1 Medicine Hat Monday 11:45 AM 4:45 PM Driver 2 Medicine Hat Tuesday 11:00 AM 7:00
                                                                                                  • Multiple Vendor SKUs

                                                                                                    One of the big concerns we have with ZOHO Inventory is lack of Vendor Skus like many other inventory software packages offer. Being able to have multiple vendor skus for the same product would be HUGE! It would populate the appropriate vendor Sku for
                                                                                                  • In Zoho Projects, is there a way to create a folders template under documents that can be used once a project is created?

                                                                                                    We have a specific folder structure that we would like to use that is standard across every project. Instead of having to create this structure every time a project is created, is there a way to create a template for the folders that can be added?
                                                                                                  • Zoho Payroll in France

                                                                                                    When will Zoho Payroll be available in France ?
                                                                                                  • Blueprint - 'On hold' state with an automatic transition?

                                                                                                    I think I'm missing something here so I'm hoping if I explain what I'm trying to achieve someone might be able to give me a way around it. We sometimes get request far in advance but we don't want to action them unless it is 7 days from when they are
                                                                                                  • HOW TO VIEW INDIVIDUAL COST OF NEWLY PURCHASED GOODS AFTER ALLOCATING LANDED COSTS

                                                                                                    Hello, I have been able to allocate landed costs to the purchase cost of the new products. however, what i need to see now is the actual cost price (original cost plus landed cost), of only my newly purchased products to enable me set a selling price
                                                                                                  • Client Script: $Client.refresh({ triggerOnLoad: true }); not triggering onLoad Client Scripts

                                                                                                    Hey friends! I'm trying to store a temporary var, refresh the page for the user, then check that temporary var and do some actions. Theoretically using the title's code: $Client.refresh({ triggerOnLoad: true }); should refresh the page and trigger on
                                                                                                  • Calculate months and years between 2 dates on subform

                                                                                                    I am looking for a function syntax for an employment candidate to calculate the number of years and months (decimal format. eg 1.2 years) they are employed. I have their start date entered, but if the end date is blank, that tells me they are still employed
                                                                                                  • Combine related grouping values into categories in CRM analytical components

                                                                                                    Hello everyone, Analyzing large datasets can be challenging when dealing with numerous individual data points. It's often difficult to extract meaningful insights when information is scattered and ungrouped. To address this, we're adding options to create
                                                                                                  • How Kiosk Studio can simplify sales for bank employees | Kiosk Studio Session #4

                                                                                                    Hello everyone, Banks can boost revenue by cross-selling to their current customers. For example, they can sell credit cards, personal loans, and more to existing account holders. To do this, bank employees move all around the CRM, open and close records,
                                                                                                  • Tip #19 - Create checkbox tracker in your spreadsheet

                                                                                                    Hello Sheet users! We are here with yet another tip to help you get the most out of Zoho Sheet. Spreadsheets can be used to handle a variety of tasks, but ever tried using checkboxes to track the progress of your action items dynamically? Here's a sample
                                                                                                  • Integrate Oracle with ZOHO CRM

                                                                                                                         Please let me know if its possible to Integrate Oracle with ZOHO CRM. If yes then help me in doing it. 
                                                                                                  • UUIDs

                                                                                                    Has anyone coded a Universal Unique Identifier (UUID) generator in Deluge?
                                                                                                  • Introducing signer groups: Streamline signature collection and make it even faster

                                                                                                    Hello everyone, We're excited to introduce signer groups, a feature designed to make your signing process quicker, more efficient, and collaborative. With signer groups, you can send an envelope to a group of people, and any member of the group can open
                                                                                                  • Calendar - Recurring Event - End of Month and Last Weekday of Month

                                                                                                    How do I set a calendar event to recur on the last day of every month? How do I set a calendar event to recur on the last weekday of the month?
                                                                                                  • Duplicate Zoho Invoices and Sales Receipts

                                                                                                    We have been running into an issue where upon saving an invoice or a sales receipt, we get a duplicate: same information saved twice but with a different invoice id/number and sales receipt id/number. I have logged a ticket but so far no response. It
                                                                                                  • Introducing revamped Zoho Creator Developer Console—a powerful platform for developing and distributing apps

                                                                                                    Hello everyone! We're thrilled to announce the launch of the revamped Zoho Creator Developer Console—a dedicated platform designed specifically for Creator developers and Partners to build, test, and distribute apps to your clients. Developer Console
                                                                                                  • Phone App of CRM doesn't find contacts

                                                                                                    I open the crm to and do a contact search but nothing comes up. If I do a full zia search it will find an old note that is attached to a contact and I can open the contact. BUT I still can't enter notes of calls, set appointments, etc. It requests I go
                                                                                                  • [Product Update] Deprecation of 'Inbound Transport Details' module in Zoho Analytics - Amazon Seller Central integration

                                                                                                    Dear Customers, Please be informed that the Amazon Seller Central will be deprecating the 'Inbound Transport Details' module APIs effective December 20, 2024. As a result, this module will no longer be supported in the Amazon Seller Central - Zoho Analytics
                                                                                                  • Is there any support for Drivers license and other forms of ID scanning capabilities?

                                                                                                    When scanning a drivers license barcode for data input to a Form, the scanning tool receives all the raw data but there doesnt seem to be a function to limit or remove the unnecessary fragmrnts, like a prefix. Is there any support or info in the help
                                                                                                  • Exciting Update: Multi WhatsApp Business Account (WABA) Support Now Available in SalesIQ!

                                                                                                    We’re pleased to share an important update that will enhance the way you manage your WhatsApp Business accounts (WABAs) within SalesIQ. With the launch of Multi WABA support, you can now connect and manage multiple brands more effectively, each under
                                                                                                  • Gravity Forms plugin not passing some fields

                                                                                                    I use the gravity form zoho plugin to push data from my lead form into my lead page in Zoho CRM. Everything was working file for about 6 months. Suddenly on Oct 1st, some of the fields are no longer getting passed to Zoho. The fields with the problem
                                                                                                  • Next Page