Quick start

The QuickBooks Online Java SDK makes it easier for Java developers to create apps for the QuickBooks Online APIs. This page describes how to create your integration, including features you will most likely want in your app.

Preliminaries

Use the links below to download the SDK, access the installation instructions, and view important information about the SDK.

    Develop an app using the Java SDK

    The following are typical steps for developing an app using the Java SDK:

    1. If you haven't already created an Intuit Developer account, create your account.
    2. Create your app on developer.intuit.com to get your development and production keys and URIs.
    3. Use API Explorer, Postman, and OAuth 2.0 Playground to explore and test the QuickBooks Online API and OAuth 2.0. For example code, see the Java sample apps. For additional tools, see Third-party tools.
    4. Develop your web app.
    5. Configure your Java SDK settings:
      1. Configure the base URL for either Sandbox or Production.
      2. Check the latest minor version supported and set this in your config file.
      3. Configure logging. 
    6. Set up authorization and implement the Connect to QuickBooks button in your app.
    7. Use your development keys for developing and testing your app in the sandbox, or production keys for Production or live QuickBooks company testing. Production keys can be obtained from the Keys tab under the Production tab of the app.
    8. Make sure that you set a unique requestId for each API call.
    9. Use the Class library reference to get details for the supported fields, functions, and classes provided by the Java SDK.
    10. For details on how to make QuickBooks Online API calls, see Make QuickBooks Online API calls.

    Configure your settings

    The Java SDK is configured with default values for settings such as minor version, number of retries, and logging. You can override these default settings by either editing the configuration file or setting the properties in your code. For details on how to configure the settings, see Configuration.

    Use the class library

    Classes provided in the Java class library correspond to the QuickBooks Online API resources. The Class Library provides wrappers for calling QuickBooks Online API resources. For example, the properties of the Account class correspond to the properties defined for the Account resource of the QuickBooks Online API.

    Make QuickBooks Online API calls

    The following sections describe how to make QuickBooks Online API calls using the Java SDK.

    Set up authorization

    For your app to access a user's data, the app redirects the user to Intuit's OAuth 2.0 server for authentication. The server authenticates the user and redirects them back to your app's OAuth 2.0 redirect URL with an authorization code, which is exchanged for an access token. Your application can use the access token to call QuickBooks Online APIs. You must refresh the token before each call to the QuickBooks Online API. For more information on setting up OAuth authorization, see Authorization. Use the OAuth 2.0 playground to experiment with the OAuth 2.0 protocol and QuickBooks Online APIs. It is pre-configured to use with Intuit's OAuth 2.0 endpoints so you can quickly get started.

    Use the RequestId parameter

    The requestId parameter uniquely identifies the HTTP request sent from the app to the service. Whenever you make a new API call, you must get a new requestId for that call. The following is an example of a basic call for a requestId:

    Context.setRequestID("unique string");
    

    The following sample code shows how to set the requestId when making a batch call:

    context = new Context(oauth, appToken, ServiceType.QBO, realmID);
    Customer customer = new Customer();
    customer.setGivenName("Mac Berry");
    customer.setDisplayName("L 34");
    BatchOperation batchOperation = new BatchOperation();
    batchOperation.addEntity(customer, OperationEnum.CREATE, "12");
    
    Customer c = GenerateQuery.createQueryEntity(Customer.class);
    String query = select($(c.getId()), $(c.getDisplayName())).generate();
    batchOperation.addQuery(query, "13");
    Context.setRequestID("987654321099");
    DataService service = new DataService(context);
    
    service.executeBatch(batchOperation);

    For details on the requestId parameter, see Making calls with the REST API. For additional useful information, see Request ID update for QuickBooks Online integration.

    Invoices

    To create and manage invoices, use the Invoice object. For information about the invoice resource, see Invoice and Create an invoice. For examples of how to perform CRUD operations using the Java SDK, see the Java CRUD sample app.

    Click to view example.
    
    // Create oauth object
    OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken,
        accessTokenSecret);
    
    // Create context
    Context context = new Context(oauth, appToken, ServiceType.QBO, companyID);
    			
    // Create dataservice
    DataService service = new DataService(context);
    
    // Add invoice
    Invoice invoice = new Invoice();
    			
    // Mandatory fields
    invoice.setDocNumber(RandomStringUtils.randomAlphanumeric(5));
    
    try {
        invoice.setTxnDate(DateUtils.getCurrentDateTime());
    } catch (ParseException e) {
        throw new FMSException("ParseException while getting current date.");
    }
    
    List customers = (List) service.findAll(new Customer());
    Customer customer = customers.get(0); //TODO handle case when there are no customers
    			
    ReferenceType customerRef = new ReferenceType();
    customerRef.setName(customer.getDisplayName());
    customerRef.setValue(customer.getId());
    invoice.setCustomerRef(customerRef);
    			
    invoice.setPrivateNote("Testing");
    invoice.setTxnStatus("Payable");
    invoice.setBalance(new BigDecimal("10000"));
    
    PhysicalAddress billingAdd = new PhysicalAddress();
    billingAdd.setLine1("123 Main St");
    billingAdd.setCity("Mountain View");
    billingAdd.setCountry("United States");
    billingAdd.setCountrySubDivisionCode("CA");
    billingAdd.setPostalCode("94043");
    invoice.setBillAddr(billingAdd);
    
    List invLine = new ArrayList();
    Line line = new Line();
    line.setDescription("test");
    line.setAmount(new BigDecimal("10000"));
    line.setDetailType(LineDetailTypeEnum.SALES_ITEM_LINE_DETAIL);
    			
    SalesItemLineDetail silDetails = new SalesItemLineDetail();
    			
    List items = (List) service.findAll(new Item());
    Item item = items.get(0); //TODO handle case when there are no items
    			
    ReferenceType itemRef = new ReferenceType();
    itemRef.setName(item.getName());
    itemRef.setValue(item.getId());
    silDetails.setItemRef(itemRef);
    
    line.setSalesItemLineDetail(silDetails);
    invLine.add(line);
    invoice.setLine(invLine);
    
    invoice.setRemitToRef(customerRef);
    
    invoice.setPrintStatus(PrintStatusEnum.NEED_TO_PRINT);
    invoice.setTotalAmt(new BigDecimal("10000"));
    invoice.setFinanceCharge(false);
    			
    Invoice savedInvoice = service.add(invoice);
    System.out.println("Invoice created: " + savedInvoice.getId() + " ::invoice doc num: " + 
        savedInvoice.getDocNumber());
    
    

    Query data

    Query filters enable your app to retrieve specific entities. For example, your app can retrieve only those customer entities that have been created within the last twenty days. The following example query retrieves customer data:

    // Create context 
    Context context = new Context(oauth, appToken, ServiceType.QBO, companyID); 
    
    // Create DataService 
    DataService service = new DataService(context); 
    
    String sql = "select * from customer"; 
    QueryResult queryResult = service.executeQuery(sql); 
    int count = queryResult.getEntities().size(); 
    System.out.println("count "+ count);
    

    For details on how to create queries, see Query filters.

    Batch calls

    Batch calls can be made to add, delete, or update data, or to make a query. The following example adds customer information using a batch call. For more information, see Batch.

    // create dataservice
    DataService service = new DataService(context);
    
    //create customer request
    Customer customer = new Customer();
    customer.setDisplayName(RandomStringUtils.randomAlphanumeric(6));
    
    //create vendor request
    Vendor vendor = new Vendor();
    vendor.setDisplayName(RandomStringUtils.randomAlphanumeric(6));
    
    //Add to batch operation
    BatchOperation batchOperation = new BatchOperation();
    batchOperation.addEntity(customer, OperationEnum.CREATE, "1");
    batchOperation.addEntity(vendor, OperationEnum.CREATE, "2");
    
    //execute batch
    service.executeBatch(batchOperation);
    Customer savedCustomer = (Customer) batchOperation.getEntity("1");
    System.out.println("Customer created: " + savedCustomer.getId());
    Vendor savedVendor = (Vendor) batchOperation.getEntity("2");
    System.out.println("Vendor created: " + savedVendor.getId());
    

    CDC calls

    Change data capture (CDC) calls return a list of entities that have changed since a specified time. This operation is useful for an app that periodically polls Data Services and then refreshes its local copy of entity data. To make CDC calls, use the CDC methods in the DataService class. The following example code makes a CDC call:

    // Create dataservice
    DataService service = new DataService(context);
    			
    List entities = new ArrayList<>();
    entities.add(new Customer());
    			
    // Perform cdc with last updated timestamp and subscribed entities
    Calendar currentDate = Calendar.getInstance();
    String cdcTimestamp = DateUtils.getStringFromDateTime(currentDate.getTime());
    
    // Call CDC
    List cdcResponse = service.executeCDCQuery(entities, cdcTimestamp);	
    if (cdcResponse.size() > 0) {
        CDCQueryResult cdcQueryresult = cdcResponse.get(0);
        Map<string,> responseMap = cdcQueryresult.getQueryResults();
        System.out.println("CDC result :: size " + responseMap.size());
    }
    System.out.println("CDC complete");
    

    For more information on making CDC calls, see Change data capture.

    Create and update custom fields

    Custom fields enable you to add attributes to existing QuickBooks objects to store information that is specific to your business. You cannot create custom fields using an API. Instead, read the Preferences entity for an existing invoice, and then update the custom field value. To update the field, send the DefinitionId of the custom field; otherwise, the update will not be successful. For more about how to update custom fields, see Create custom fields.

    Generate reports

    To generate reports, create a ReportService object. The following code provides an example for generating a report. For more about generating reports, see Reports.

    // Create context
    Context context = new Context(oauth, appToken, ServiceType.QBO, companyID);
    
    // Create dataservice
    ReportService service = new ReportService(context);
    		
    service.setStart_date("2017-01-01"); 			
    service.setEnd_date("2017-12-31");
    service.setAccounting_method("Accrual");
    Report report = service.executeReport(ReportName.BALANCESHEET.toString());
    System.out.println("Report name: " + report.getHeader().getReportName()  );
    

    Create and read a TaxCode

    To create a TaxCode object, use GlobalTaxService. To read a TaxCode object, create an Intuit.Ipp.Data.TaxService object as shown in the following example. For more information, see Manage tax for US locales or Manage tax for non-US locales.

    // Create context
    Context context = new Context(oauth, appToken, ServiceType.QBO, companyID);
    			
    // Create tax service
    TaxService taxservice = new TaxService();
    taxservice.setTaxCode("MyTaxCode" + UUID.randomUUID());
    
    TaxRateDetails trd = new TaxRateDetails();
    trd.setRateValue(BigDecimal.ONE);
    trd.setTaxAgencyId("1"); // create tax agency first and use that id
    trd.setTaxRateName("MyTaxRate" + UUID.randomUUID());
    trd.setTaxApplicableOn(TaxRateApplicableOnEnum.SALES);
    	        
    List taxRateDetails = new ArrayList();
    taxRateDetails.add(trd);
    taxservice.setTaxRateDetails(taxRateDetails);       
    	      
    // Create globaltaxService
    GlobalTaxService taxdataservice = new GlobalTaxService(context);
    TaxService ts = taxdataservice.addTaxCode(taxservice);
    System.out.println("tx code id " + ts.getTaxCodeId());
    

     

    Attachments

    A file, such as a receipt image, product photo, or note, can be linked to a transaction or Item object. For details about attachments, see Attach images and notes.

    Attach a note to a transaction using an Attachable endpoint

    Notes can be linked to an object using the Attachable and AttachableRef classes, as shown in the following example. For details, see Attach images and notes.

    Click to view example.
    // Create dataservice
    DataService service = new DataService(context);
    			
    // Add attachable with minimum mandatory fields
    Attachable attachable = new Attachable();
    attachable.setLat("25.293112341223");
    attachable.setLong("-21.3253249834");
    attachable.setPlaceName("Fake Place");
    attachable.setNote("Attachable note " + RandomStringUtils.randomAlphanumeric(5));
    attachable.setTag("Attachable tag " + RandomStringUtils.randomAlphanumeric(5));
    			
    // Create attachRef for customer
    AttachableRef attachableRef1 = new AttachableRef();
    List customers = (List) service.findAll(new Customer());
    Customer customer = customers.get(0); //TODO handle case when there are no customers
    
    ReferenceType customerRef = new ReferenceType();
    customerRef.setName(customer.getDisplayName());
    customerRef.setValue(customer.getId());
    customerRef.setType("Customer");
    attachableRef1.setEntityRef(customerRef);
    			
    List list = new ArrayList();
    list.add(attachableRef1);
    			
    attachable.setAttachableRef(list);
    attachable.setCategory(AttachableCategoryEnum.OTHER.value());
    			
    // Add attachable
    Attachable savedAttachable = service.add(attachable);
    System.out.println("Attachable  created: " + savedAttachable.getId());
    

    Attach a file to a transaction using an Upload endpoint

    Use the Attachable and AttachableRef classes to attach a file to a transaction by uploading an endpoint as shown in the following example, which uploads an image attachment using an HTTP endpoint.. For more on uploading attachments using an endpoint, see Attachments.

    Click to view example.
    // Create dataservice
    DataService service = new DataService(context);
    			
    // Get the attachable, in this case we are randomly retrieving a attachable
    Attachable attachable = new Attachable();
    attachable.setLat("25.293112341223");
    attachable.setLong("-21.3253249834");
    attachable.setPlaceName("Fake Place");
    attachable.setNote("Attachable note " + RandomStringUtils.randomAlphanumeric(5));
    attachable.setTag("Attachable tag " + RandomStringUtils.randomAlphanumeric(5));
    			
    attachable.setFileName(RandomStringUtils.randomAlphanumeric(5) + ".pdf");
    attachable.setContentType("application/pdf");
    			
    // Create attachRef for invoice
    AttachableRef ref = new AttachableRef();
    List invoices = (List) service.findAll(new Invoice());
    Invoice invoice = invoices.get(0); //TODO handle case when there are no invoices
    ReferenceType invoiceRef = new ReferenceType();
    invoiceRef.setValue(invoice.getId());
    invoiceRef.setType("Invoice");
    ref.setEntityRef(invoiceRef);
    			
    List listAttachRef = new ArrayList<>();
    listAttachRef.add(ref);
    attachable.setAttachableRef(listAttachRef);
    			
    // Get the base64 content from file 		
    File file = new File("location_of_the_file_to_upload"); //TODO update file location
    InputStream in = new FileInputStream(file);
    			
    // Call the upload api
    Attachable attachableOutput = service.upload(attachable, in);		
    System.out.println("File name " + attachableOutput.getFileName() + " attached:: Id " +
        attachableOutput.getId());
    			
    

    Did you find this page helpful?
    Your feedback helps us make our docs better. Please let us know if this page helped you, or if it needs improvement.

     Got Questions? Get Answers in our developer forums.